- This topic has 6 replies, 4 voices, and was last updated 1 month, 1 week ago by
April 16, 2020 at 12:22 am #219345
When an error occurs in a script I have been attempting to capture the error message from the Error object:
# this doesn't seem to work $msg = $Error.Message
My understanding is the $Error is a collection of exceptions. I have tried various ways to access the object and also looked at the Format-List * output.
Can anyone suggest the best way to capture the error message from a Error[n] object?
Business Case: clear, concise error logging; do not desire the whole exception object.
April 16, 2020 at 12:27 am #219360ParticipantTopics: 12Replies: 519Points: 1,194Rank: Community Hero
April 16, 2020 at 12:28 am #219363
Cool – thanks!
April 16, 2020 at 1:37 am #219378ParticipantTopics: 17Replies: 24Points: 80Rank: Member
I know this was already answered, just wanted to add that for me what helped.
get-aduser – name blah -erroraction stop
$CaughtError = $_
This ensures no matter what the error is caught in a variable and you can do something with it.
Another thing just in case you need it.
Then you can use $CaughtError.Exception.Getype().Fullname in case you wanted to trap a specific error then a catch all error.
Hope this helps.
April 16, 2020 at 5:51 am #219420Senior ModeratorTopics: 8Replies: 1215Points: 4,334Rank: Community Hero
April 16, 2020 at 12:09 pm #219525
Thanks for your response! It makes sense to use try-catch since the logic probably needs to be halted.
April 16, 2020 at 12:12 pm #219531
@kvprasoon – good to know! (Thanks) We are targeting the lowest common denominator since this code has to work in a variety of environments. Seems there is still some Win 2012 running PS 4 in use. I would have hoped for at least PS 5.1. I am looking forward to the rest of the world catching up!
Thanks for your response.
- You must be logged in to reply to this topic.