Powershell 查找孤立进程

Powershell 查找孤立进程

我正在寻找一种方法来查找没有父进程运行的进程(孤立进程)。我尝试使用 win32_process 来执行此操作。我有一个返回所需属性的查询,这是我正在努力进行的比较:

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

我尝试过对两个数组使用 compare-object -includeequal 并得到大量结果 - 以至于我怀疑该运算符的真实性,因为我输入的数组太多了。我认为 diff 命令中增加了一些值,但除了输入数组之外,我不太熟悉其他用法。有人有使用 diff 命令和/或其他解决方案的经验吗?

最终目标是比较或区分上述 wmi 调用中的两个数组:

$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

然后仅返回未同时出现在两者中的项(孤立项)。提前致谢!

答案1

我知道这是一个老问题,但以下解决方案效果很好:

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
}

答案2

可能效率不高,但似乎有效:

$all_Processes = gwmi win32_process -ComputerName . | select ProcessID,ParentProcessID,Description,@{l="Username";e={$_.getowner().user}} | where{$_.Username -like $env:username}
$all_processIDs = $all_Processes.Processid #ARRAY1
$parent_processIDs = $all_Processes.ParentProcessId #ARRAY2

# create a new Array for parents that are gone
$gone = New-Object System.Collections.ArrayList

# loop through all processes
$parent_processIDs | Sort-Object -Unique | ForEach-Object {
# find the ones where the current parent ID is not running
    if ($all_processIDs -notcontains $_)
    {
        $gone.Add($_) | Out-Null
    }
}
# now we have all parentIDs no longer running

# loop through all processes and find those in that list
$all_Processes | Where-Object {$gone -contains $_.ParentProcessId} | ForEach-Object {$_}

相关内容