【问题标题】:Powershell how to get the ParentProcessID by the ProcessIDPowershell如何通过ProcessID获取ParentProcessID
【发布时间】:2015-11-25 08:09:50
【问题描述】:

我无法从拥有 ProcessID 的进程中获取 ParentProcessID。我试过这样,这就是它与 ProcessID 的工作方式:

$p = Get-Process firefox
$p.Id

但如果我尝试使用 ParentProcessID,它就不起作用:

$p.ParentProcessId

有没有办法通过 ProcessID 获取 ParentProcessID?

【问题讨论】:

  • 是的,但不是使用 Get-Process。您需要使用 CIM/WMI (Win32_Process)
  • gwmi win32_process 这样的事情?
  • 是的,类似的。 Get-CimInstance Win32_Process -Filter "Name = 'firefox.exe'"|select ParentProcessId
  • 是的,它可以工作,但我想通过 ProcessID 选择它我找到了解决方案,我会将它作为 anwser 发布,谢谢你的帮助。

标签: powershell


【解决方案1】:

如 cmets 中所述,从 Get-Process (System.Diagnostics.Process) 返回的对象不包含父进程 ID。

为此,您需要检索 Win32_Process 类的实例:

PS C:\> $ParentProcessIds = Get-CimInstance -Class Win32_Process -Filter "Name = 'firefox.exe'"
PS C:\> $ParentProcessIds[0].ParentProcessId
3816

【讨论】:

    【解决方案2】:

    这对我有用:

    $p = Get-Process firefox
    $parent = (gwmi win32_process | ? processid -eq  $p.Id).parentprocessid
    $parent
    

    输出如下:

    1596
    

    1596 是匹配的 ParentProcessID,我已经用 ProcessExplorer 进行了检查。

    【讨论】:

      【解决方案3】:

      在 PowerShell Core 中,Get-Process cmdlet 返回的 Process 对象包含一个 Parent 属性,该属性为您提供父进程对应的 Process 对象。

      例子:

      > $p = Get-Process firefox
      > $p.Parent.Id
      

      【讨论】:

      • 请注意,这需要(提升的)管理员权限。否则它会静默失败,Parent 成员将是$nullWMI solution 以较少的权限工作。
      【解决方案4】:

      我想获取当前正在运行的 PS 进程的 PPID,而不是通过名称查找另一个进程。以下对我回到 PS v2 有用。 (我没有测试 v1...)

      $PPID = (gwmi win32_process -Filter "processid='$PID'").ParentProcessId
      Write-Host "PID: $PID"
      Write-Host "PPID: $PPID"
      

      【讨论】:

        猜你喜欢
        • 2011-03-26
        • 1970-01-01
        • 2018-12-02
        • 2014-06-19
        • 1970-01-01
        • 2011-03-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多