繁体   English   中英

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

[英]Powershell Start Process, Wait with Timeout, Kill and Get Exit Code

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

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

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

之前,我没有等待超时,但只是在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. 获取进程的退出代码

您可以使用$proc | kill更简单地终止进程 $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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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