【问题标题】:How to wait and kill a timeout process in Powershell如何在 Powershell 中等待并终止超时进程
【发布时间】:2016-06-07 07:02:21
【问题描述】:

在 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

虽然进程没有被杀死,但即使在 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
}

【问题讨论】:

    标签: windows powershell


    【解决方案1】:

    如果你想杀死整个进程树,你还需要找到并停止子进程。

    这是一篇很好的文章,解释了它并向您展示了如何做到这一点:

    http://powershell.com/cs/blogs/tobias/archive/2012/05/09/managing-child-processes.aspx

    【讨论】:

    • 链接不存在了。
    【解决方案2】:

    我推入了 github 小项目,该项目可用于为他和他的子进程运行进程和设置超时:https://github.com/burlachenkok/process_tool

    它是 Makefile 的源代码,而不是 powershell 脚本。不过希望对你有用。

    【讨论】:

      猜你喜欢
      • 2010-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-21
      • 1970-01-01
      • 2020-09-09
      • 1970-01-01
      相关资源
      最近更新 更多