Powershell 启动进程、超时等待、杀死并获取退出代码

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

我怎样才能
  • 启动进程
  • 等待它有序执行并完成
  • 如果崩溃(例如命中超时),则将其杀死
  • 获取进程退出代码
  • 最佳答案

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

    关于Powershell 启动进程、超时等待、杀死并获取退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36933527/

    相关文章:

    DOS批处理文件中的Perl脚本返回值

    c# - 从异常处理程序获取 ExitCode

    azure - Azure 门户中的 Powershell : This module requires Az. 帐户版本 2.12.5。在当前 PowerShell session 中导入早期版本的 Az.Accounts

    windows - 捕获程序stdout和stderr来分隔变量

    mysql - 利用 MySQL 查询结果

    windows - 使用 Powershell 停止/启动 Microsoft Windows 集群角色

    c# - 在方法内部等待,直到事件被捕获

    wcf - 如何正确等待WCF异步

    java - 在现有元素上执行 javascript 时,GhostDriver 抛出陈旧异常 "Element does not exist in cache"

    powershell - 为什么我的 PowerShell 退出代码始终为 "0"?