Really Kill that Excel Object

If you’ve tried to use Excel 2007 or above with any of your Powershell scripts, you know that more often than not, when you quit Excel, a process stays running.  Not a huge deal until you’ve got a script scheduled to run several times a week and you end up silly with memory-eating Excel processes. You could kill all EXCEL.EXE processes, but what if you’ve got a scheduler that may be running other Excel processes as well?  If you kill all  running EXCEL.EXE processes, you’ll also be killing other Excel processes that should be running.

I’ve managed to put together some code that will determine what Excel processes are running before your create your Excel object and kill only the process spawned by your script.

## Grab all EXCEL.EXE processes before we create our Excel object.  This will find
## all Excel processes that we don't want to kill.  After we have those, we create
## our Excel object and immediately look at the Excel processes afterward.  There
## obviously a slight chance that you'll grab a process that spawned between our
## $startprocs and $endprocs scans, but it's a pretty small chance.
$startprocs = Get-Process | Where {($_.Name.ToLower() -eq "excel")}
$excel      = New-Object -ComObject Excel.Application
$endprocs   = Get-Process | Where {($_.Name.ToLower() -eq "excel")}
//             Your Code Goes Here                                        //
## Try to quit Excel (after you've saved your doc).  It's probably not going to work,
## but we're gonna try anyway.
## Check to make sure $startprocs isn't null.  If it is null and we don't check, the
## script will blow.  If $startprocs is null, we're going to kill the only running
## Excel process...the one we created.
If($startprocs -gt $null)
     $compare = Compare-Object $startprocs $endprocs
     $process  = $compare | % {If($_.SideIndicator -match "=>") {$_.InputObject}}
     $process = $endprocs
Kill -Id $process.Id

2 thoughts on “Really Kill that Excel Object

Leave a Reply

Your email address will not be published. Required fields are marked *