PowerShell 通过句柄获取进程

PowerShell Get process by its handle

$ActiveHandle = [UserWindows]::GetForegroundWindow()
$Process = Get-Process | ? {$_.MainWindowHandle -eq $ActiveHandle}

此代码检索当前活动 window 的标题。问题是它只通过 MainWindowHandle 过滤进程。例如,如果我的活动句柄是来自同一进程的弹出窗口,它不会 return 任何东西,因为句柄不是它的主句柄。如何修改代码以检查所有句柄而不仅仅是主要句柄?或者更确切地说,如何检索所有进程句柄? 我不想使用像 WASP 这样的外部工具。

您可以为此使用 the GetWindowThreadProcessId Win32 API function

# Define a type that allows us to call the relevant win32 api
$user32 = Add-Type -MemberDefinition @'
[DllImport("user32.dll", SetLastError=true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
'@ -PassThru -Name user32Func

# prepare a variable to receive the target process id
$procId = 0

# call the function with, pass the handle as the first argument
$threadId = $user32::GetWindowThreadProcessId($ActiveHandle, [ref]$procId)

# If the owning thread and process was identified, the return-value will have been non-0
if($threadId) {
  Write-Host "Found process $(Get-Process -Id $procId |% Name) with PID $procId"
}
else {
  Write-Host "No owning process found"
}