Powershell script termination examples

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
}


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
}

if you want a cleanup function after you use ctrl+c, you could use the function as I provided, but you would need to make the vars in the global scope(e.g. $global:writers), OR dot-source when running the script (. .\myscript.ps1), then calling Close-Script after ctrl+cA Finally block runs even if you use CTRL+C to stop the script. A Finally block also runs if an Exit keyword stops the script from within a Catch block.

See the following example. Run it and cancel it by pressing ctrl-c.

try
{
    while($true)
    {
        "Working.."
        Start-Sleep -Seconds 1
    }
}
finally
{
    write-host "Ended work."
}