How to connect to existing instance of Excel from PowerShell?

风流意气都作罢 提交于 2019-12-17 17:07:02

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11081317/how-to-connect-to-existing-instance-of-excel-from-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!