Run code on powershell script termination to close files?
Might try using Try/Catch/Finally, putting your close() commands in the Finally block.
With PowerShell 2.0 and up, you can define a Trap
which will fire when a terminating error occurs. You can define multiple traps to capture different exceptions. This could result in much cleaner code than try/catch
littered everywhere, or wrapping the entire script in one big try/catch
.
To terminate a script, use exit
.If an exception is thrown, use try/catch/finally
with close() commands in finally
. If it's just an if-test, try something like this:
function Close-Script { #If stream1 is created if($stream1) { $stream1.Close() } #Terminate script exit}$stream1 = New-Object System.IO.StreamWriter filename.txtIf(a test that detects your error) { Close-Script}
If the amounts of streamwriters varies from time to time, you can collect them to an array and close them. Ex:
function Close-Script { #Close streams $writers | % { $_.Close() } #Terminate script exit}$writers = @()$stream1 = New-Object System.IO.StreamWriter filename.txt$writers += $stream1$stream2 = New-Object System.IO.StreamWriter filename2.txt$writers += $stream2If(a test that detects your error) { Close-Script}