gpt4 book ai didi

powershell - 获取COM服务器的PID

转载 作者:行者123 更新时间:2023-12-03 00:55:11 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

好的,我找到了解决方法,我们需要调用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

关于powershell - 获取COM服务器的PID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4024113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com