Last active
April 1, 2017 14:48
-
-
Save Jimmy-Xu/d7707ff433ae99f5a8335bd11a0a57b4 to your computer and use it in GitHub Desktop.
递归获取父进程
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#usage: | |
# Import-Module ./get-parent-process.psm1 -Force | |
## example | |
# Get-ParentProcess -Name CExecSvc | |
# Get-ChildProcess -Name CExecSvc | |
function Get-ParentProcess { | |
[cmdletbinding()] | |
param( | |
[parameter(mandatory=$true,position=1)][string]$Name | |
) | |
#main | |
try { | |
$Id = (get-process -Name $Name).Id; | |
$ErrorActionPreference = "Stop"; | |
$ParentId = ""; | |
$Prefix = ""; | |
while($Id -ne "") | |
{ | |
if($ParentId -eq ""){ | |
echo "$Name $Id"; | |
} | |
$ParentId = (wmic process where ProcessId=$Id get ParentProcessId).split("=")[1].Trim(); | |
if($Id -eq $ParentId) | |
{ | |
break; | |
} | |
$Name = (wmic process where ProcessId=$ParentId get Name).split("=")[1].Trim(); | |
$Prefix = "+$Prefix"; | |
echo "$Prefix $Name $ParentId"; | |
$Id = $ParentId; | |
} | |
} catch{ | |
Write-Host "Done"; | |
} | |
} | |
function Get-ChildProcess { | |
[cmdletbinding()] | |
param( | |
[parameter(mandatory=$true,position=1)][string]$Name | |
) | |
#main | |
try { | |
$Id = (get-process -Name $Name).Id; | |
$ErrorActionPreference = "Stop"; | |
$i = 0; | |
foreach($item in (wmic process where ParentProcessId=$Id get Name,ProcessId)) | |
{ | |
if ($i -eq 0) | |
{ | |
echo "$Name $Id"; | |
} | |
if (($i % 2) -eq 0) | |
{ | |
$Name = $item.split("=")[1].Trim(); | |
} | |
else | |
{ | |
$ProcessId = $item.split("=")[1].Trim(); | |
echo "- $Name $ProcessId"; | |
$Name = ""; | |
$ProcessId = ""; | |
} | |
$i++ | |
} | |
} catch{ | |
Write-Host "Done"; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment