Reputation: 1910
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.
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).
Upvotes: 6
Views: 10117
Reputation: 58491
cudo's to mklement0 and nordmanden
You can use CIM cmdlets to filter on the ParentProcessId of a given process and use it in a recursive function to get an entire tree
function Get-ChildProcesses ($ParentProcessId) {
$filter = "parentprocessid = '$($ParentProcessId)'"
Get-CIMInstance -ClassName win32_process -filter $filter | Foreach-Object {
$_
if ($_.ParentProcessId -ne $_.ProcessId) {
Get-ChildProcesses $_.ProcessId
}
}
}
Called like this
Get-ChildProcesses 4 | Select ProcessId, Name, ParentProcessId
Note that a process can terminate (by user, crash, done, ...) and the ID can get recycled. In theory, you can end up wit ha tree of processes all having Notepad as parent process.
Upvotes: 10
Reputation: 18857
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
Upvotes: 0