3

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

pico
  • 1,660
  • 4
  • 22
  • 52

2 Answers2

4

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.

Lieven Keersmaekers
  • 57,207
  • 13
  • 112
  • 146
  • As an aside: The CIM cmdlets (e.g., `Get-CimInstance`) superseded the WMI cmdlets (e.g., `Get-WmiObject`) in PowerShell v3 (released in September 2012). Therefore, the WMI cmdlets should be avoided, not least because PowerShell (Core) v6+, where all future effort will go, doesn't even _have_ them anymore. Note that WMI still _underlies_ the CIM cmdlets, however. For more information, see [this answer](https://stackoverflow.com/a/54508009/45375). – mklement0 Dec 18 '21 at 02:37
  • Hes asking for the exact opposite, how do you get the child id from the parent id, not the parent id from the child id. – nordmanden Mar 14 '22 at 17:53
  • 1
    @nordmanden - tx, completely missed that part in the original post. – Lieven Keersmaekers Mar 14 '22 at 18:59
0

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
Hackoo
  • 18,337
  • 3
  • 40
  • 70