使用Powershell关闭excel应用程序

时间:2016-07-21 12:26:28

标签: excel vba excel-vba powershell

我在PowerShell的工作簿中启动一个宏(以自动化一个进程)。 powershell中的以下内容打开excel工作簿并运行宏而无需可视化过程。

问题是即使我没有看到宏运行,从宏生成的新excel实例仍然是打开的。

# 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

excel文件仍然作为任务管理器中的进程出现并占用内存空间。

如何让powershell完全关闭通过宏打开的excel应用程序的实例?

enter image description here

任何帮助都非常感谢!

3 个答案:

答案 0 :(得分:3)

在释放COM对象之前尝试使用退出方法,如下所示:

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

答案 1 :(得分:1)

您可以将其添加到PS代码中:

kill -processname excel

这将关闭所有打开的Excel实例

答案 2 :(得分:0)

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