我想在循环中重复执行一个程序。
有时,程序会崩溃,所以我想杀死它以便下一次迭代可以正确启动。我通过超时确定这一点。
我有超时工作,但无法获得程序的退出代码,我还需要确定其结果。
之前,我没有超时等待,只是在 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/