PowerShell在超时后不会停止程序。

huangapple go评论70阅读模式
英文:

powershell does not stop program after timeout

问题

以下是翻译好的部分:

要创建 Windows 版本的 GNU 超时功能(作为一个嵌入到批处理脚本中的一行代码),用于启动程序,并在它在超时后不自行终止时终止它。

powershell.exe "Start-Process 'ping.exe' -ArgumentList '127.0.0.1', '-t' -NoNewWindow -PassThru | % { $_.WaitForExit(3000) }; If(!$?) { $_.Kill() }

仅在超时后打印 FALSE,但 ping 程序继续运行。我做错了什么?

英文:

Want to make windows equivalent for GNU timeout (as a oneliner to embed into batch script) to start program and terminate it if this doea on terminate itself after timeout.

powershell.exe "Start-Process 'ping.exe' -ArgumentList '127.0.0.1', '-t' -NoNewWindow -PassThru | % { $_.WaitForExit(3000) }; If(!$?) { $_.Kill() }"

It only print FALSE after timeout, but ping program continue. What am I doing wrong?

答案1

得分: 2

$? 保存了上一个 命令调用 的错误状态,而 $_.WaitForExit(3000) 不是一个命令。

从您收到的输出来看,WaitForExit() 方法在目标进程在超时之前没有退出时返回 $false,所以您应该检查 值:

... | % { if (-not $_.WaitForExit(3000)) { $_.Kill() } }
英文:

$? holds the error status for the last command invocation, and $_.WaitForExit(3000) is not a command.

As evident from the ouput you receive, the WaitForExit() method returns $false if the target process didn't exit before the timeout was exceeded, so you'll want to inspect that value instead:

... |% { if(-not $_.WaitForExit(3000)) { $_.Kill() } }

huangapple
  • 本文由 发表于 2023年3月31日 17:43:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75897023.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定