Reputation: 771
I am working in PowerShell and trying to figure out how custom Try Catch statements work. My current major issue involves mixing Try/Catch and If statements. So the idea of what I am trying to achieve is something like this:
try {
if (!$someVariable.Text) { throw new exception 0 }
elseif ($someVariable.Text -lt 11) { throw new exception 1 }
elseif (!($someVariable.Text -match '[a-zA-Z\s]')) { throw new exception 2}
}
catch 0 {
[System.Windows.Forms.MessageBox]::Show("Custom Error Message 1")
}
catch 1 {
[System.Windows.Forms.MessageBox]::Show("Custom Error Message 2")
}
catch 2 {
[System.Windows.Forms.MessageBox]::Show("Custom Error Message 3")
}
Now I know the above code is very inaccurate in terms of what the actual code will be, but I wanted to visually display what I'm thinking and trying to achieve.
Does anyone know how to create custom error messages with PowerShell that could assist me with achieving something close to the above idea and explain your answer a bit? Thank you in advance
So far, the link below is the closest thing I have found to what I'm trying to achieve:
PowerShell Try, Catch, custom terminating error message
Upvotes: 3
Views: 30093
Reputation: 6860
The Error you throw is stored at $_.Exception.Message
$a = 1
try{
If($a -eq 1){
throw "1"
}
}catch{
if ($_.Exception.Message -eq 1){
"Error 1"
}else{
$_.Exception.Message
}
}
Upvotes: 3
Reputation: 19694
I would suggest using the $PSCmdlet
ThrowTerminatingError()
method. Here's an example:
Function New-ErrorRecord
{
param(
[String]$Exception,
[String]$ExceptionMessage,
[System.Management.Automation.ErrorCategory] $ErrorCategory,
[String] $TargetObject
)
$e = New-Object $Exception $ExceptionMessage
$errorRecord = New-Object System.Management.Automation.ErrorRecord $e, $ErrorID, $ErrorCategory, $TargetObject
return $ErrorRecord
}
Try
{
If (not condition)
{
$Error = @{
Exception = 'System.Management.Automation.ParameterBindingException'
ExceptionMessage = 'Error text here'
ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidArgument
TargetObject = ''
}
$PSCmdlet.ThrowTerminatingError((New-ErrorRecord @Error))
}
} Catch [System.Management.Automation.ParameterBindingException]
{
'do stuff'
}
Upvotes: 2