Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect to existing instance of Excel from PowerShell?

All examples that automate Excel through PowerShell start with this line:

PS> $Excel = New-Object -Com Excel.Application

This seems to be handling a new instance of Excel, e.g. running $Excel.Visible = $true will show an empty, blank Excel window, not switch to the existing workbook.

If there is already an instance of Excel running, is there a way to connect to it?

like image 463
Borek Bernard Avatar asked Jun 18 '12 10:06

Borek Bernard


2 Answers

Instead of the usual New-Object -ComObject excel.application us this

$excel = [Runtime.Interopservices.Marshal]::GetActiveObject('Excel.Application')

Rest stays the same.

One downside. You will only get the excel "instances" started by the same user that will initiate the ps1.

like image 67
user2587683 Avatar answered Oct 01 '22 16:10

user2587683


Yes, you can access the COM object via HWND [Window handle] using this WIN32 API (AccessibleObjectFromWindow).

(See a SO post sample here of using this api via C#)

.

You may have to write an assembly in C# and/or manipulate P/Invoke calls via Powershell.

You may give a shot at it & see how it goes.

like image 23
Angshuman Agarwal Avatar answered Oct 01 '22 16:10

Angshuman Agarwal