Matt Simmons
Matt Simmons

Reputation: 708

Run code on powershell script termination to close files?

I've got a script that's chewing through a lot of objects, and sometimes I want to kill it in the middle of the run because I see something going south. Unfortunately, I'm writing to a log file using System.IO.StreamWriter, and whenever I send a Ctrl-C, my log files are stuck open.

Is there any way I can define some kind of handler or exiting function that allows me to gracefully close filehandles and connections that I have open?

Upvotes: 4

Views: 3131

Answers (3)

alroc
alroc

Reputation: 28174

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.

Upvotes: 2

Frode F.
Frode F.

Reputation: 54881

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.txt


If(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 += $stream2

If(a test that detects your error) {
    Close-Script
}

Upvotes: 1

mjolinor
mjolinor

Reputation: 68273

Might try using Try/Catch/Finally, putting your close() commands in the Finally block.

Upvotes: 4

Related Questions