给定进程 ID 在 PowerShell 中终止进程树 [英] Terminate process tree in PowerShell given a process ID

查看:119
本文介绍了给定进程 ID 在 PowerShell 中终止进程树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我从 PowerShell 运行了几个进程:

Lets say I run a couple of processes from PowerShell:

$p1 = $(Start-Process -PassThru ./example.exe)
$p2 = $(Start-Process -PassThru ./example.exe)

example.exe 将生成几个同名的子进程.

example.exe is going to spawn a few child processes with the same name.

我如何只是$p1 和它的子进程,而不杀死$p2 和它的子进程?

How do I kill just $p1 and its child processes, without killing $p2 and its child processes?

只运行Stop-Process $p1 只会杀死父进程$p1,让它的子进程继续运行.

Just running Stop-Process $p1 only kills the parent process $p1, leaving it's children running.

到目前为止我看到的所有答案都涉及杀死具有特定名称的所有进程,但这在这里不起作用.

All of the answers I seen so far involve killing all of the processes with a certain name, but that will not work here.

推荐答案

所以我真的找不到一个很好的方法来做到这一点,所以我写了一个帮助函数,它使用递归来遍历进程树:

So I couldn't really find a good way to do this, so I wrote a helper function that uses recursion to walk down the process tree:

function Kill-Tree {
    Param([int]$ppid)
    Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq $ppid } | ForEach-Object { Kill-Tree $_.ProcessId }
    Stop-Process -Id $ppid
}

要使用它,请将其放在 PowerShell 脚本中的某个位置,然后像这样调用它:

To use it, put it somewhere in your PowerShell script, and then just call it like so:

Kill-Tree <process_id>

这篇关于给定进程 ID 在 PowerShell 中终止进程树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆