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?
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.