简体   繁体   English

powershell,如何仅给定父进程 ID 获取子进程 ID

[英]powershell, how to get process-id of children given only the parent process-id

Let's say I start a powershell process like this:假设我像这样开始一个 powershell 进程:

    $procid = start-process -FilePath powershell _
       -ArgumentList ping, -t, localhost

How can I get the Process-Id of "ping" given only the process-id of powershell, ie.仅给定 powershell 的进程 ID,即,如何获取“ping”的进程 ID。 $procid? $procid?

Because, I only have $procid in a script, and need to find procid of child processes.因为,我在脚本中只有 $procid,需要找到子进程的 procid。

在此处输入图像描述

Here you can see that powershell has pid 3328, and I need to use 3328 to query powershell to find the id: 7236 (Ping.exe).这里可以看到powershell的pid为3328,我需要用3328查询powershell找到id:7236(Ping.exe)。

You can use WMI to get the ParentProcessId of a given process您可以使用 WMI 获取给定进程的 ParentProcessId

Get-WmiObject -Class Win32_Process -Filter "name ='ping.exe'" | 
    Select-Object ParentProcessId

Note that most of the time this will be the actual parent process but a process can terminate (by user, crash, done, ...) and the ID can get recycled.请注意,大多数情况下,这将是实际的父进程,但进程可以终止(由用户、崩溃、完成……)并且 ID 可以被回收。 In theory, you can end up in a tree of processes all having Notepad as parent process.从理论上讲,您最终可以在所有以记事本作为父进程的进程树中结束。

Here is another example using the command line ping :这是使用命令行ping的另一个示例:

$ping_exe = cmd.exe /c where ping #This line will store the location of ping.exe in $ping_exe variable.
$Array_Links = @("www.google.com","www.yahoo.com","www.stackoverflow.com","www.reddit.com","www.twitter.com")
ForEach ($Link in $Array_Links) {
    Start $ping_exe $Link
}

Get-WmiObject -Class Win32_Process -Filter "name ='ping.exe'" | 
    Select-Object ParentProcessId,ProcessId,CommandLine

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM