Pages

onsdag 27. februar 2013

PowerShell: Try-Catch

When writing PowerShell scripts it can be usefull to process the errors in a logical manner. To do this use the Try-Catch-Finally structure. For instance:

try {
    # Catch all errors
    $ErrorActionPreference = "Stop"
    # Delete Crap from registry
    Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" -Name "Crap"
}
catch [System.Exception] {
    # So if things go wrong, write out a message.
    $Fullname = $_.Exception.GetType().FullName
    Write-Output "Error in $($_.InvocationInfo.ScriptName)"
    Write-Output "At Line: $($_.InvocationInfo.ScriptLineNumber) Char: $($_.InvocationInfo.OffsetInLine) ($Fullname)"
    Write-Output $_.Exception.Message
    break
}
finally {
    # Set Error Action to its default
    $ErrorActionPreference = "Continue"
}