poi*_*000 7 windows powershell
在Windows 7桌面中使用Powershell 2.0
我想创建一个运行ant命令的进程,然后等待该进程在几分钟内完成.如果超时并且进程仍在运行,那么我想杀死它.
我写了一些代码如下:
$p = Start-Process "cmd.exe" '/c ant execute' -PassThru -RedirectStandardOutput $log_file_path
Wait-Process -id $p.ID -timeout 100
if(!$p.hasExited) {
echo "kill the process"
$p.Kill()
#Stop-Process $p.ID
}
Start-Sleep -s 30
# continue to do other things
Run Code Online (Sandbox Code Playgroud)
尽管该过程没有被杀死,但即使在Start-Sleep语句执行后它仍然在运行.
我也尝试使用Stop-Process命令,因为注释掉的行表明,没有运气,该过程仍在运行.
我可能错过了一些重要的事情,请提供一些线索.
编辑:
事实证明,有一些子进程仍然在cmd窗口中运行,只杀死cmd进程是不够的.
我终于通过以下代码完成了工作:
if(!$p.hasExited) {
echo "kill the process"
taskkill /T /F /PID $p.ID
#$p.Kill()
#Stop-Process $p.ID
}
Run Code Online (Sandbox Code Playgroud)
如果要杀死整个进程树,还需要找到并停止子进程。
这是一篇很好的文章,解释了它并向您展示了如何做到这一点:
http://powershell.com/cs/blogs/tobias/archive/2012/05/09/managing-child-processes.aspx