How to get Unix as atexit in Powershell?

When creating an OLE object, you must release it at the end of the program. Otherwise, the process will run in the background.

I wrote the following example:

$excel = New-Object -ComObject Excel.Application

# some long running code here

finally
{
  "running finally"
  [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
}

      

When I stop the script with Ctrl- Cduring the "long code" in the middle, the finally block doesn't run. Whenever I do this, I only get one process EXCEL.EXE

in the process table.

How can I reliably release a COM object even if the user interrupts the script with Ctrl- C?

+1


source to share


1 answer


Try Engine Events (only works in the console, not PowerShell ISE):



# Set up automatic functionality on engine exit.
Register-EngineEvent PowerShell.Exiting -SupportEvent -Action {
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
}

      

0


source







All Articles