Skip to content

Instantly share code, notes, and snippets.

@aroben
Created May 8, 2013 18:34
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aroben/5542538 to your computer and use it in GitHub Desktop.
Save aroben/5542538 to your computer and use it in GitHub Desktop.
Script to print a process tree on Windows
$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.CommandLine) {
$Description = $Process.CommandLine
} 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 "PID", "Command Line")
Write-Output ("{0,6} {1}" -f "---", "------------")
foreach ($Process in ($ProcessesWithoutParents | Sort-Object CreationDate)) {
Show-ProcessTree $Process.ProcessId 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment