3

I want to write a Powershell script to invoke an executable on a remote machine by its path and then wait for it to finish running. This is what I've got so far:

$executable = "C:\Temp\example.exe"
$session = New-PSSession -ComputerName VIRTUALMACHINE
$job = Invoke-Command -Session $session -ScriptBlock {$executable} -AsJob
Wait-Job -Job $job

Instead of running C:\Temp\example.exe, the remote machine runs the string $executable - not exactly what I was going for here!

How do I fix this?

Void Star
  • 2,401
  • 4
  • 32
  • 57

2 Answers2

2

Using some information from Bacon Bits' answer, information from this answer, and some information from this answer, I managed to piece together a solution.

$executable = "C:\Temp\example.exe"
$session = New-PSSession -ComputerName VIRTUALMACHINE
Invoke-Command -Session $session -ScriptBlock {Start-Process $using:executable -Wait}

The script block I was using before would run $executable as a script, that is return the value of $executable in the remote session, which just doesn't work at all. This doesn't get the local value of $executable, and it wouldn't run the executable anyway even if it did. To get the local value to the remote session, $using:executable will serve, but it still isn't being executed. Now, using Start-Process $using:executable will run the exeutable, as will &$using:executable or Invoke-Expression $using:executable, but it doesn't appear to work as the job will complete immediately. Using Start-Process $using:executable -Wait will achieve the originally intended task, although there are many ways to do this I think.

I will wait on accepting this as an answer until other people have had time to suggest perhaps better answers or correct any misinformation I may have given here.

Community
  • 1
  • 1
Void Star
  • 2,401
  • 4
  • 32
  • 57
1

You need the call operator (&) to execute a string as though it were a script, or Invoke-Expression, or Start-Process. Try {&$executable} or {iex $executable} or {Start-Process $executable}.

Each one functions slightly different, so you should definitely test them. In my experience, you have to fiddle with them to get them to do what you want and behave the way you want.

Bacon Bits
  • 30,782
  • 5
  • 59
  • 66
  • None of these are working - it's always trying to execute what I give it literally instead of treating $executable like the variable it is. And besides, I can just call an executable from a Powershell session without & or Invoke-Expression or Start-Process and that seems to work. – Void Star Aug 06 '15 at 17:08
  • If you can get it working and then show me some actual code that would be appreciated. – Void Star Aug 06 '15 at 17:09