PoshCode Archive  Artifact [449b4efa51]

Artifact 449b4efa518a6895d4b6ecceff0eb2ec1594090ff683892c12f758a85f79603c:

  • File Looks-for-parent-process.ps1 — part of check-in [d5a1b22fcd] at 2018-06-10 13:42:53 on branch trunk — 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. (user: greg zakharov size: 1586)

# 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}
    }
  }
}