function Print-ProcessTree() {
function Get-ProcessAndChildProcesses($Level, $Process) {
$cmdLine = if ($Process.CommandLine -eq $null) { $Process.Name } else { $Process.CommandLine.SubString(0, [Math]::Min(200, $Process.CommandLine.Length)) }
"{0}[{1,5}] - {2}" -f (" " * $Level), $Process.ProcessId, $cmdLine
$Children = $AllProcesses | where-object {$_.ParentProcessId -eq $Process.ProcessId -and $_.CreationDate -ge $Process.CreationDate}
if ($null -ne $Children) {
foreach ($Child in $Children) {
Get-ProcessAndChildProcesses ($Level + 1) $Child
}
}
}
$AllProcesses = Get-CimInstance -ClassName "win32_process"
$RootProcesses = @()
foreach ($Process in $AllProcesses[1..($AllProcesses.length-1)]) {
$Parent = $AllProcesses | where-object {$_.ProcessId -eq $Process.ParentProcessId -and $_.CreationDate -lt $Process.CreationDate}
if ($null -eq $Parent) {
$RootProcesses += $Process
}
}
"[{0,5}] - {1}" -f $AllProcesses[0].ProcessId, $AllProcesses[0].Name
foreach ($Process in $RootProcesses) {
Get-ProcessAndChildProcesses 0 $Process
}
}
Print-ProcessTree