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

时间:2016-04-29 08:38:15

标签: powershell wait exit-code 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
    }
}

我怎么能

  1. 启动流程
  2. 等待它有序地执行并完成
  3. 如果崩溃(例如命中超时),则将其杀死
  4. 获取流程退出代码

1 个答案:

答案 0 :(得分:10)

您可以使用$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
    }
}