Home > front end >  powershell, how to get process-id of children given only the parent process-id
powershell, how to get process-id of children given only the parent process-id

Time:12-01

Let's say I start a powershell process like this:

    $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. $procid?

Because, I only have $procid in a script, and need to find procid of child processes.

enter image description here

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).

CodePudding user response:

You can use WMI to get the ParentProcessId of a given process

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. In theory, you can end up in a tree of processes all having Notepad as parent process.

CodePudding user response:

Here is another example using the command line 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
  • Related