Closing Excel Gracefully

by Nov 15, 2011

When you access Microsoft Excel from script, you may have noticed that it never gets removed from memory again, even if you call its Quit() method:

'Excel processes: {0}' -f @(Get-Process excel -ea 0).Count
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $True
Start-Sleep 5
$excel.Quit()
'Excel processes: {0}' -f @(Get-Process excel -ea 0).Count

Now you could try and kill that orphaned process:

Stop-Process -name excel

However, you now would kill all open Excel instances, not just the one you launched from script. Also, killing a process with Stop-Process is hostile, and Excel may complain the next time you launch it that it was shut down unexpectedly.

Here is how you tell the .NET Framework to quit Excel peacefully:

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

Twitter This Tip!
ReTweet this Tip!