的PID我在PowerShell中創建一個COM對象,像這樣:獲取COM服務器
$application = new-object -ComObject "word.application"
有沒有辦法讓推出MS Word實例的PID(或其他唯一標識符)?
我想檢查程序是否被阻止例如通過模態對話框詢問密碼,而且我無法從PowerShell中做到這一點。
的PID我在PowerShell中創建一個COM對象,像這樣:獲取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
您可以使用
get-process -InputObject <Process[]>
這並不工作: 獲取進程:無法綁定參數「InputObject」。無法將「System .__ ComO bject#{000208d5-0000-0000-c000-000000000046}」類型的「System .__ ComObject」值轉換爲鍵入「System.Diagnostics.Process」。 – 2010-10-26 14:34:59