I need to write a PS script that outputs process tree with child processes nested under the parent processes. It needs to identify all processes with no parent processes as the root for the trees.
I am NOT a PS programmer, not even a little bit so I need assistance please. Found some examples that kinda give me what I am looking for but need some guidance...:
Processes need to be identified at the root of trees and nest children under parents. I have attached an example picture of what the output should look like:
Thank you!
I am NOT a PS programmer, not even a little bit so I need assistance please. Found some examples that kinda give me what I am looking for but need some guidance...:
Code:
$ProcessesById = @{}
foreach ($Process in (Get-WMIObject -Class Win32_Process)) {
$ProcessesById[$Process.ProcessId] = $Process
}
$ProcessesWithoutParents = @()
$ProcessesByParent = @{}
foreach ($Pair in $ProcessesById.GetEnumerator()) {
$Process = $Pair.Value
if (($Process.ParentProcessId -eq 0) -or !$ProcessesById.ContainsKey($Process.ParentProcessId)) {
$ProcessesWithoutParents += $Process
continue
}
if (!$ProcessesByParent.ContainsKey($Process.ParentProcessId)) {
$ProcessesByParent[$Process.ParentProcessId] = @()
}
$Siblings = $ProcessesByParent[$Process.ParentProcessId]
$Siblings += $Process
$ProcessesByParent[$Process.ParentProcessId] = $Siblings
}
function Show-ProcessTree([UInt32]$ProcessId, $IndentLevel) {
$Process = $ProcessesById[$ProcessId]
$Indent = " " * $IndentLevel
if ($Process.name) {
$Description = $Process.name
} else {
$Description = $Process.Caption
}
Write-Output ("{0,6}{1} {2}" -f $Process.ProcessId, $Indent, $Description)
foreach ($Child in ($ProcessesByParent[$ProcessId] | Sort-Object CreationDate)) {
Show-ProcessTree $Child.ProcessId ($IndentLevel + 4)
}
}
Write-Output ("{0,6} {1}" -f "Id", "Process Name")
Write-Output ("{0,6} {1}" -f "---", "------------")
foreach ($Process in ($ProcessesWithoutParents | Sort-Object CreationDate)) {
Show-ProcessTree $Process.ProcessId 0
}
Processes need to be identified at the root of trees and nest children under parents. I have attached an example picture of what the output should look like:
Thank you!