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.Visiable = $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?
Instead of the usual
-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.
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.