Powershell启动过程,等待超时,终止并获取退出代码

And*_*iff 11 powershell exit-code wait start-process

我想在循环中重复执行一个程序.

有时,程序崩溃,所以我想杀死它,以便下一次迭代可以正确启动.我通过超时确定这个.

我有超时工作,但无法获得程序的退出代码,我还需要确定其结果.

之前,我没有等待超时,但只是在Start-Process中使用了-wait,但是如果启动的程序崩溃,这会使脚本挂起.通过这种设置,我可以正确地获得退出代码.

我正在从ISE执行.

for ($i=0; $i -le $max_iterations; $i++)
{
    $proc = Start-Process -filePath $programtorun -ArgumentList $argumentlist -workingdirectory $programtorunpath -PassThru
    # wait up to x seconds for normal termination
    Wait-Process -Timeout 300 -Name $programname
    # if not exited, kill process
    if(!$proc.hasExited) {
        echo "kill the process"
        #$proc.Kill() <- not working if proc is crashed
        Start-Process -filePath "taskkill.exe" -Wait -ArgumentList '/F', '/IM', $fullprogramname
    }
    # this is where I want to use exit code but it comes in empty
    if ($proc.ExitCode -ne 0) {
       # update internal error counters based on result
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎么能够

  1. 开始一个过程
  2. 等待它有序地执行并完成
  3. 如果崩溃则杀死它(例如命中超时)
  4. 获取进程的退出代码

Mar*_*ndl 15

您可以使用$proc | kill或更简单地终止该过程$proc.Kill().请注意,在这种情况下您将无法检索退出代码,您应该只更新内部错误计数器:

for ($i=0; $i -le $max_iterations; $i++)
{
    $proc = Start-Process -filePath $programtorun -ArgumentList $argumentlist -workingdirectory $programtorunpath -PassThru

    # keep track of timeout event
    $timeouted = $null # reset any previously set timeout

    # wait up to x seconds for normal termination
    $proc | Wait-Process -Timeout 4 -ErrorAction SilentlyContinue -ErrorVariable timeouted

    if ($timeouted)
    {
        # terminate the process
        $proc | kill

        # update internal error counter
    }
    elseif ($proc.ExitCode -ne 0)
    {
        # update internal error counter
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你是对的,我以为Wait-Process会回复一些东西.我编辑了我的答案,现在我将错误消息分配给$ timeouted,如果发生超时,则设置. (2认同)
  • @AlekDavis 不,你省略了那里的“$”符号。 (2认同)