Struggling with Error Object

Hi,

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[0].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.

Thanks!

$_.Exception.Message

Cool - thanks!

I know this was already answered, just wanted to add that for me what helped.

Try {

get-aduser - name blah -erroraction stop
}

Catch {

$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.

@MoodIndigo, for your use case, PowerShell 7 has new error views introduced. Below link gives you all you want.

https://www.petri.com/how-error-handling-works-in-powershell-7

Hi Jason,
Thanks for your response! It makes sense to use try-catch since the logic probably needs to be halted.
Thanks.

@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.