【问题标题】:Powershell start-process -wait parameter fails in remote script blockPowershell start-process -wait 参数在远程脚本块中失败
【发布时间】:2014-06-09 22:21:17
【问题描述】:

所以这是我正在尝试做的一个示例:

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

它可以很好地连接到另一台机器,并且可以正常启动进程。问题是它在继续之前不会等待该过程完成。这会导致问题。有什么想法吗?

快速编辑:为什么远程运行进程时-Wait参数会失败?

【问题讨论】:

  • 似乎是 Powershell 版本 3 的问题,而不是版本 2。

标签: powershell remoting invoke-command start-process


【解决方案1】:

我之前遇到过一次,IIRC,解决方法是:

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]

【讨论】:

  • 这个变通办法的问题是 $process.ExitCode 没有设置
【解决方案2】:

这是 Powershell 版本 3 的问题,但不是版本 2,其中 -Wait 可以正常工作。

在 Powershell 3 中 .WaitForExit() 对我有用:

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

只需 Start-Sleep 直到 .HasExited - 不设置 .ExitCode,通常最好知道您的 .exe 是如何完成的.

【讨论】:

    【解决方案3】:

    您也可以使用 System.Diagnostics.Process 类解决此问题。如果您不关心输出,您可以使用:

    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()
    }
    

    如果你在乎,你可以做类似以下的事情:

    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()
    }
    

    这将等待进程完成,然后返回标准输出流。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 2019-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      • 1970-01-01
      相关资源
      最近更新 更多