相关疑难解决方法(0)

如何在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)

windows powershell

7
推荐指数
1
解决办法
1万
查看次数

标签 统计

powershell ×1

windows ×1