假设我从 PowerShell 运行了几个进程:
$p1 = $(Start-Process -PassThru ./example.exe)
$p2 = $(Start-Process -PassThru ./example.exe)
Run Code Online (Sandbox Code Playgroud)
example.exe 将产生几个同名的子进程。
如何在不杀死及其子进程的情况下杀死just 及其子进程?$p1$p2
只是运行Stop-Process $p1只会杀死父进程$p1,让它的子进程继续运行。
到目前为止,我看到的所有答案都涉及杀死具有特定名称的所有进程,但这在这里不起作用。
whe*_*ler 10
所以我真的找不到一个好的方法来做到这一点,所以我写了一个帮助函数,它使用递归来遍历进程树:
function Kill-Tree {
Param([int]$ppid)
Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq $ppid } | ForEach-Object { Kill-Tree $_.ProcessId }
Stop-Process -Id $ppid
}
Run Code Online (Sandbox Code Playgroud)
要使用它,请将它放在 PowerShell 脚本中的某个位置,然后像这样调用它:
Kill-Tree <process_id>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4325 次 |
| 最近记录: |