0

Suppose I type a code like this:

$excel = [Runtime.InteropServices.Marshal]::GetActiveObject("Excel.Application")

It will only work if I only have one Excel application open. If I have two Excel applications open, $excel might reference to the wrong one. Is there a way to reference to a specific Excel application, for example, based on its filename or its window title?

vxs8122
  • 834
  • 2
  • 10
  • 22

1 Answers1

0

I use this:

$sig = @"
[DllImport("user32.dll", SetLastError=true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
"@
Add-Type -MemberDefinition $sig -Namespace User32 -Name Util -UsingNamespace System.Text
$p=0
[User32.util]::GetWindowThreadProcessId($MSExcel.HWND, [ref]$p) |out-null
Get-Process -id $p | Stop-Process

To be honest I don't remember where I got it (I sure didn't write it), but it's worked for my needs to be able to end the Excel window that my script specifically launched.

TheMadTechnician
  • 34,906
  • 3
  • 42
  • 56