【问题标题】:Get PID of COM server获取 COM 服务器的 PID
【发布时间】:2011-04-30 18:16:24
【问题描述】:

我在 powershell 中创建了一个 com 对象,如下所示:

$application = new-object -ComObject "word.application"

有没有办法获取启动的 MS Word 实例的 PID(或其他一些唯一标识符)?

我想检查程序是否被阻止,例如通过模式对话框询问密码,而我不能从 PowerShell 中做到这一点。

【问题讨论】:

    标签: powershell com ms-word pid


    【解决方案1】:

    好的,我找到了方法,我们需要调用 Windows API。诀窍是获取 HWND,它在 Excel 和 Powerpoint 中公开,但在 Word 中不公开。获得它的唯一方法是将应用程序窗口的名称更改为唯一的名称并使用“FindWindow”找到它。然后,我们可以使用“GetWindowThreadProcessId”函数获取PID:

    Add-Type -TypeDefinition @"
    using System;
    using System.Runtime.InteropServices;
    
    public static class Win32Api
    {
    [System.Runtime.InteropServices.DllImportAttribute( "User32.dll", EntryPoint =  "GetWindowThreadProcessId" )]
    public static extern int GetWindowThreadProcessId ( [System.Runtime.InteropServices.InAttribute()] System.IntPtr hWnd, out int lpdwProcessId );
    
    [DllImport("User32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    }
    "@
    
    
    $application = new-object -ComObject "word.application"
    
    # word does not expose its HWND, so get it this way
    $caption = [guid]::NewGuid()
    $application.Caption = $caption
    $HWND = [Win32Api]::FindWindow( "OpusApp", $caption )
    
    # print pid
    $myPid = [IntPtr]::Zero
    [Win32Api]::GetWindowThreadProcessId( $HWND, [ref] $myPid );
    "PID=" + $myPid | write-host
    

    【讨论】:

      【解决方案2】:

      你可以使用

       get-process -InputObject <Process[]>
      

      【讨论】:

      • 这不起作用:Get-Process:无法绑定参数“InputObject”。无法将“System.__ComO bject#{000208d5-0000-0000-c000-000000000046}”类型的“System.__ComObject”值转换为“System.Diagnostics.Process”类型。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-30
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多