Execute code on powershell script completion to close files?
I have a script that chews on a lot of objects, and sometimes I want to kill it in the middle of a run because I see something to the south. Unfortunately I am writing to a log file using System.IO.StreamWriter and whenever I send Ctrl-C my log files are closed.
Is there some way to define some kind of handler or exit function that allows me to gracefully close file descriptors and connections that are being opened?
You can try using Try / Catch / finally by placing your close () commands in a finally block.
With PowerShell 2.0 and up, you can define Trap
which one to fire when a terminating error occurs. You can define multiple hooks to catch various exceptions. This can lead to significantly cleaner code than getting try/catch
littered all over the place, or wrapping the entire script in one big one try/catch
.
To terminate the 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.txt
If(a test that detects your error) {
Close-Script
}
If the number of threadmen changes from time to time, you can collect them into an array and close them. Example:
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 += $stream2
If(a test that detects your error) {
Close-Script
}