简体   繁体   中英

Powershell start-process -wait parameter fails in remote script block

So here's a sample of what I'm trying to do:

Invoke-Command [Connection Info] -ScriptBlock {
    param (
        [various parameters]
    )
    Start-Process [some .exe] -Wait
} -ArgumentList [various parameters]

It connects to the other machine just fine, and launches the process fine. The problem is it doesn't wait for the process to complete before moving on. This causes issues. Any ideas?

Quick edit: why does the -Wait parameter fail when running the process remotely?

I ran into this once before, and IIRC, the workaround was:

Invoke-Command [Connection Info] -ScriptBlock {
    param (
        [various parameters]
    )
    $process = Start-Process [some .exe] -Wait -Passthru

    do {Start-Sleep -Seconds 1 }
     until ($Process.HasExited)

} -ArgumentList [various parameters]

This is the problem with Powershell version 3, but not version 2 where -Wait works as it should.

In Powershell 3 .WaitForExit() does the trick for me:

$p = Start-Process [some .exe] -Wait -Passthru
$p.WaitForExit()
if ($p.ExitCode -ne 0) {
    throw "failed"
}

Just Start-Sleep until .HasExited - doesn't set .ExitCode , and it's usually good to know how your .exe finished.

You can also work around this by using the System.Diagnostics.Process class. If you do not care about the output you can just use:

Invoke-Command [Connection Info] -ScriptBlock {
$psi = new-object System.Diagnostics.ProcessStartInfo
$psi.FileName = "powershell.exe"
$psi.Arguments = "dir c:\windows\fonts"
$proc = [System.Diagnostics.Process]::Start($psi)
$proc.WaitForExit()
}

If you do care you can do something similar to the following:

Invoke-Command [Connection Info] -ScriptBlock {
$psi = new-object System.Diagnostics.ProcessStartInfo
$psi.FileName = "powershell.exe"
$psi.Arguments = "dir c:\windows\fonts"
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$proc = [System.Diagnostics.Process]::Start($psi)
$proc.StandardOutput.ReadToEnd()
}

This will wait for the process to complete and then return the standard output stream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM