Reputation: 1315
I've problems to get the ParentProcessID from a Process where I have the ProcessID. I tried it like this, this is how it works with the ProcessID:
$p = Get-Process firefox
$p.Id
But if I try it with the ParentProcessID, it doesn't work:
$p.ParentProcessId
Is there a way to get the ParentProcessID by the ProcessID?
Upvotes: 20
Views: 34828
Reputation: 1905
Here a recursive function to get a simple process tree. It uses the Get-CimInstance cmdlet and defaults to the PID of the current shell:
$id = $PID; $tree = @()
do {
$p = Get-CimInstance -ClassName Win32_Process -Filter "ProcessId = '$id'"
$tree += "$($p.ProcessId) $($p.Name)"
$id = $p.ParentProcessId
} while ($id)
echo $tree
which gives
51100 pwsh.exe
73932 conhost.exe
50252 powershell.exe
13544 WindowsTerminal.exe
11984 explorer.exe
or
52220 pwsh.exe
11144 sihost.exe
3916 svchost.exe
1488 services.exe
1344 wininit.exe
depending on initial PID and invocation of PowerShell. I wanted to use Get-Process, but the returned Process object's Parent property (undocumented in the docs!) would be null on sihost.
Upvotes: 0
Reputation: 2309
PowerShell (Core 6 at least) have CodeProperty Parent
on Process
.
[System.Diagnostics.Process]::GetCurrentProcess().Parent
NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName
------ ----- ----- ------ -- -- -----------
53 128,45 68,27 144,38 102672 1 WindowsTerminal
Upvotes: 1
Reputation: 11096
I wanted to get the PPID of the current running PS process, rather than for another process looked up by name. The following worked for me going back to PS v2. (I didn't test v1...)
$PPID = (gwmi win32_process -Filter "processid='$PID'").ParentProcessId
Write-Host "PID: $PID"
Write-Host "PPID: $PPID"
Upvotes: 2
Reputation: 1576
In PowerShell Core, the Process
object returned by Get-Process
cmdlet contains a Parent property which gives you the corresponding Process
object for the parent process.
Example:
> $p = Get-Process firefox
> $p.Parent.Id
Upvotes: 15
Reputation: 1315
This worked for me:
$p = Get-Process firefox
$parent = (gwmi win32_process | ? processid -eq $p.Id).parentprocessid
$parent
The output is the following:
1596
And 1596
is the matching ParentProcessID I've checked it with the ProcessExplorer.
Upvotes: 15
Reputation: 174990
As mentioned in the comments, the objects returned from Get-Process
(System.Diagnostics.Process
) doesn't contain the parent process ID.
To get that, you'll need to retrieve an instance of the Win32_Process class:
PS C:\> $ParentProcessIds = Get-CimInstance -Class Win32_Process -Filter "Name = 'firefox.exe'"
PS C:\> $ParentProcessIds[0].ParentProcessId
3816
Upvotes: 22