Jason Crawford
asked on
PowerShell error handling best practices
Question on PowerShell error handling. Which method is 'better' and why?
Using Try/Catch to handle any errors for Do-Something
Using Try/Catch to handle any errors for Do-Something
try {
Do-Something -ErrorAction 'Stop'
}
catch {
$errormessage = $_.Exception.Message
Write-Verbose "An error occurred: $errormessage"
}
Using an If statement to handle errors for Do-Somethingif (Do-Something) {
Do-SomethingElse
}
else {
$errormessage = $_.Exception.Message
Write-Verbose "An error occurred: $errormessage"
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
what is the result you are getting, and what is the result you are expecting?
ASKER
The specific results don't matter I'm just asking from a best practices point of view for my own education.
The best answer is try the (Try,Catch) but if it doesn't work in your scenario then move to the next option, and that's checking the results, and if that doesn't work, then pull the source a second time and verify you have changed what you wanted.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
That's an interesting thought though. For instance if I wanted to take action when a MailContact isn't found I could catch the specific error generated for object not found:
try {
Get-MailContact $_
}
catch [ManagementObjectNotFoundException] {
Enable-MailUser $aduser.samaccountname -ExternalEmailAddress $_
Set-MailUser $_ -EmailAddresses @{add=$contact.emailaddresses}
}
catch {
Write-Verbose "An error occurred: $($error[0].exception.message)"
}
Thanks for helping me talk this through.
ASKER
Open in new window
Is there a better way to do this?