Close excel application using Powershell

只愿长相守 提交于 2020-01-02 09:21:13

问题


I am initiating a macro in a workbook from powershell (to automate a process). The below in powershell opens the excel workbook and runs the macro without visualizing the process.

The issue is even though I do not see the macro running, the new instance of excel generated from the macro is still open.

# start Excel
$excel = New-Object -comobject Excel.Application

#open file
$FilePath = 'C:\file\Book1.xlsm'
$workbook = $excel.Workbooks.Open($FilePath)


#access the Application object and run a macro
$app = $excel.Application
$app.Run("macro")


#close excel
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
Start-Sleep 1
'Excel processes: {0}' -f @(Get-Process excel -ea 0).Count
Remove-Variable $excel

exit $LASTEXITCODE

The excel file still comes up as a process in task manager and is taking up memory space.

How do I have powershell completely close the instance of the excel application that opens through the macro?

Any help greatly appreciated!


回答1:


Try using Quit method before you release COM object, like this:

$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
Remove-Variable excel



回答2:


You could add this to your PS code:

kill -processname excel

This will close all open instances of Excel




回答3:


Creating the Excel file:

$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $True
...

Closing down the Excel file:

$Excel.Close()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
spps -n Excel


来源:https://stackoverflow.com/questions/38504265/close-excel-application-using-powershell

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