Powershell启动过程,等待超时,终止并获取退出代码 [英] Powershell Start Process, Wait with Timeout, Kill and Get Exit Code

查看:375
本文介绍了Powershell启动过程,等待超时,终止并获取退出代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想循环执行一个程序.

I want to repeatedly execute a program in a loop.

有时候,程序崩溃了,所以我想杀死它,以便下一次迭代可以正确开始.我是通过超时来确定的.

Sometimes, the program crashes, so I want to kill it so the next iteration can correctly start. I determine this via timeout.

我正在超时,但是无法获取程序的退出代码,我还需要确定其结果.

I have the timeout working but cannot get the Exit Code of the program, which I also need to determine its result.

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

Before, I did not wait with timeout, but just used -wait in Start-Process, but this made the script hang if the started program crashed. With this setup I could correctly get the exit code though.

我正在从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()终止该过程.请注意,在这种情况下,您将无法检索退出代码,而应该更新内部错误计数器:

You can terminate the process more simply using $proc | kill or $proc.Kill(). Be aware, that you won't be able to retrieve a exit code in this case, you should rather just update the internal error counter:

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

这篇关于Powershell启动过程,等待超时,终止并获取退出代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆