views:

18

answers:

2

I create a com object in powershell like so:

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

Is there a way to get the PID (or some other unique identifier) of the launched MS Word instance?

I want to check if the program is blocked e.g. by modal dialogs asking for passwords, and I can't do it from whithin PowerShell.

Thx!

A: 

you may be able to use

 get-process -InputObject <Process[]>
Orbit
That doesn't work:Get-Process : Cannot bind parameter 'InputObject'. Cannot convert the "System.__ComObject" value of type "System.__ComObject#{000208d5-0000-0000-c000-000000000046}" to type "System.Diagnostics.Process".
Buddy Casino
A: 

Ok, I found out how to do it, we need to call the Windows API. The trick is to get the HWND, which is exposed in Excel and Powerpoint, but not in Word. The only way to get it is to change the name of the application window to something unique and find it using "FindWindow". Then, we can get the PID using the "GetWindowThreadProcessId" function:

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
Buddy Casino