Windows – Powershell find orphaned processes

diff()powershellprocesswindowswmi

I am looking for a way to find processes that do not have a parent process running (orphaned processes). Im attempting to do this using win32_process. I have the query that returns the attributes needed, its the comparison im struggling with:

gwmi win32_process -ComputerName $hostname | select ProcessID,ParentProcessID,@{l="Username";e={$_.getowner().user}} | where{$_.Username -like $username}

I have tried compare-object -includeequal against the two arrays and get an overwhelming number of results- so much so i doubt truth of the operator given the arrays i'm feeding it. I think there is value added in the diff command, but am not familiar with the usage other than feeding it arrays as well. Does anyone have experience with the diff command and/or another solution?

The end goal is to compare or diff the two arrays from the above wmi call:

$proc_all = gwmi win32_process -ComputerName $hostname | select ProcessID,ParentProcessID,@{l="Username";e={$_.getowner().user}} | where{$_.Username -like $username}
$sub_procs = $proc_all.Processid #ARRAY1
$par_proces = $proc_all.ParentProcessId #ARRAY2

And then return only the ones that do not appear in both (orphaned). Thanks in advance!

Best Answer

I know this is an oldie, but following solution performs quite well:

function Get-OrphanedProcesses {
  $procsWithParent = Get-WmiObject -ClassName "win32_process" | Select-Object ProcessId,ParentProcessId
  $orphaned = $procsWithParent | Where-Object -Property ParentProcessId -NotIn $procsWithParent.ProcessId

  Get-Process | Where-Object -Property Id -In $orphaned.ProcessId
}