Struggling with Error Object

Welcome Forums General PowerShell Q&A Struggling with Error Object

Viewing 6 reply threads
  • Author
    Posts
    • #219345
      Participant
      Topics: 5
      Replies: 12
      Points: 72
      Rank: Member

      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!

    • #219360
      Participant
      Topics: 12
      Replies: 519
      Points: 1,194
      Helping Hand
      Rank: Community Hero

      $_.Exception.Message

    • #219363
      Participant
      Topics: 5
      Replies: 12
      Points: 72
      Rank: Member

      Cool – thanks!

    • #219378
      Participant
      Topics: 17
      Replies: 24
      Points: 80
      Rank: Member

      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.

    • #219420
      Senior Moderator
      Topics: 8
      Replies: 1215
      Points: 4,334
      Helping Hand
      Rank: Community Hero

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

      How Error Handling Works in PowerShell 7

      • This reply was modified 1 month, 1 week ago by kvprasoon. Reason: post correction
    • #219525
      Participant
      Topics: 5
      Replies: 12
      Points: 72
      Rank: Member

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

    • #219531
      Participant
      Topics: 5
      Replies: 12
      Points: 72
      Rank: Member

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

Viewing 6 reply threads
  • You must be logged in to reply to this topic.