# encoding: ascii
# api: powershell
# title: Looks for parent process
# description: Why? WHY IT NEED USE WIN32_PROCESS TO CHECK PARENT PROCESS FOR ANOTHER PROCESS??? There is PerformanceCounter class in the System.Diagnostics namespace which can help you determine parent process for a process easily.
# version: 0.1
# type: function
# author: greg zakharov
# license: CC0
# function: Get-ParentProcess
# x-poshcode-id: 4548
# x-archived: 2015-07-16T03:25:26
# x-published: 2015-10-24T11:51:00
#
#
function Get-ParentProcess {
<#
.LINK
Follow me on twitter @gregzakharov
http://msdn.microsoft.com/en-US/library/system.diagnostics.performancecounter.aspx
Get-Process
#>
param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String]$ProcessName
)
begin {
ps | % {$hash = @{}}{
$pc = New-Object Diagnostics.PerformanceCounter("Process", "Creating Process ID", $_.ProcessName)
try {
$ps = [Diagnostics.Process]::GetProcessById($pc.RawValue)
$hash[$pc.InstanceName] = $pc.RawValue
}
catch {
$hash[$pc.InstanceName] = -1
}
}
}
process {
[Diagnostics.Process]::GetProcessesByName($ProcessName) | % {
if ($hash[$_.ProcessName] -ne -1) {
foreach ($p in @(ps -id $hash[$ProcessName])){
'"{0}" (PID {1}) is parent for "{2}" (PID {3})"' -f $p.ProcessName, $p.Id, $_.ProcessName, $_.Id
}
}
else { Write-Host `"$ProcessName`" has not parent process. -fo cyan}
}
}
}