已知父进程PID,如何在PowerShell中查询其子进程的进程ID
PowerShell通过父进程ID查询子进程ID的实现方案
适用场景:
你通过以下方式启动了PowerShell进程并持有其PID:$procid = Start-Process -FilePath powershell -ArgumentList ping, -t, localhost -PassThru | Select-Object -ExpandProperty Id需要通过已有的
$procid查询到其子进程(比如示例中的ping.exe)的PID。
方法1:CIM查询(全版本兼容)
该方案兼容PowerShell 5.1及以上所有版本,无需额外依赖,直接调用系统接口实现:
# 填入你持有的父进程ID $targetParentPid = $procid # 查询所有子进程对象 $childProcessList = Get-CimInstance -ClassName Win32_Process | Where-Object { $_.ParentProcessId -eq $targetParentPid } # 直接提取所有子进程的PID列表 $childPidList = $childProcessList | Select-Object -ExpandProperty ProcessId # 如需同时查看进程名与PID,执行以下命令即可 $childProcessList | Select-Object ProcessId, Name
在你给出的示例场景中,代入$procid=3328后执行,即可直接获取到ping.exe对应的PID 7236。
方法2:PowerShell 7+ 简化写法
如果你使用PowerShell 7及以上版本,Get-Process原生支持父进程属性查询,写法更简洁:
Get-Process | Where-Object { $_.Parent.Id -eq $procid } | Select-Object Id, ProcessName
注意事项
- 仅当父进程仍处于运行状态时查询结果准确,若父进程已退出,部分系统的进程父ID字段不会自动更新,可能无法查询到对应子进程
- 若父进程启动了多个子进程,返回结果会是包含所有子进程PID的数组,可根据进程名进一步筛选
内容的提问来源于stack exchange,提问作者pico
相关产品推荐
相关产品推荐

