获取COM服务器的PID

时间:2010-10-26 13:26:30

标签: powershell com ms-word pid

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

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

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

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

2 个答案:

答案 0 :(得分:3)

好的,我发现了怎么做,我们需要调用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

答案 1 :(得分:0)

您可以使用

 get-process -InputObject <Process[]>
相关问题