Error handling
Published 13 June 2018
Error handling
There are many ways to handle errors in PowerShell, and depending on your situation, one approach may be better than others.
As of PowerShell V2, you can also use ‘Try/Catch’ instead of `trap`. ‘Try/Catch’ is aimed more at developers than administrators, it doesn’t introduce scope as ‘trap’ does, it supports finally and rethrowing of exceptions. As such, it is typically preferable and the examples in this document will focus on `Try/Catch`.
A classic example of a try catch statement
try {
#logic
throw "Error message"
}
catch {
exit #optional
}
Example 1
Running the following without installing the necessary cmdlets for SQL Clone.
try {
Connect-Sqlclone http://localhost:14145
}
catch {
exit
}
Example 2
function log ([string]$msg){ #logging functionality
#logging code, such as email, log to database etc. For this example, just output it to the console
Write-Output($msg)
}
#Create a clone from an existing image
Connect-SqlClone 'http://localhost:14145'
$Image = Get-SqlCloneImage -Name {Image_Name}
$SqlServerInstance = Get-SqlCloneSqlServerInstance -MachineName {Machine_Name} -InstanceName {Instance_Name}
New-SqlClone -Name {New_Clone} -Location $SqlServerInstance -Image $Image | Wait-SqlCloneOperation
#Get the newly created clone
$ClonesToDelete = Get-SqlClone -Name {New_Clone}
try {
#Update the clone name to make it fail for this example
$ClonesToDelete = Get-SqlClone -Name 'A_New_Unique_Name'
#Attempt to delete the clone
Remove-SqlClone -Clone $ClonesToDelete |
Wait-SqlCloneOperation
}
catch {
log $_.exception.message #send the exception message for logging
exit #terminate the script
}