英文:
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() } }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论