Skip to content

Instantly share code, notes, and snippets.

@stephent23
Created July 11, 2016 19:33
Show Gist options
  • Save stephent23/91176e82a41ed4dd98b3ec2398c8470b to your computer and use it in GitHub Desktop.
Save stephent23/91176e82a41ed4dd98b3ec2398c8470b to your computer and use it in GitHub Desktop.
The Gist shows two examples of custom PowerShell errors.
# Example 1 - Catch the exception that would have been thrown after a method such as connecting to a SQL database / failed network connection
$errorRecord = New-Object System.Management.Automation.ErrorRecord(
$_.Exception,
'SmallOneWordDescriptionOfError', (e.g.ConnectionFailureToDBName)
[System.Management.Automation.ErrorCategory]::ConnectionError,
$myinvocation
)
$pscmlet.ThrowTerminatingError($errrorRecord)
# Example 2 - Creating and throwing a custom error for parameters that are incorrect for example
$errorRecord = New-Object System.Management.Automation.ErrorRecord(
(New-Object System.ArgumentException "The parameter provided is wrong because"),
'SmallOneWordDescriptionOfError', (e.g.ConnectionFailureToDBName)
[System.Management.Automation.ErrorCategory]::InvalidArgument,
$VariableName
)
$pscmlet.ThrowTerminatingError($errrorRecord)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment