PowerTip: Check to See if a Command Completes Properly

PowerTip: Check to See if a Command Completes Properly

  • Comments 2
  • Likes

Summary:  Learn how to check for proper completion of a Windows PowerShell command.

Hey, Scripting Guy! Question How can I tell if a Windows PowerShell command completes successfully?

               

 Hey, Scripting Guy! Answer

a. Query the $error automatic variable. If $error[0] reports no information, no errors have occurred.

b. Query the $? automatic variable. If $? is equal to true, the command completed successfully.

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • hi,

    Thanks Ed, here is also:

    c. $LastExitCode

    PS II> replace

    PS II> $LastExitCode

    11

    d. ErrorVariable parameter

    PS II> get-item 1:\xoo -ErrorAction 0 -ErrorVariable foo

    PS II> if($foo) { write-error "error !!" }

    e. try catch finally

    PS II> try {

     $PreferenceErrorAction=$ErrorActionPreference

     $ErrorActionPreference = 'stop'

     command....

    }

    catch {

     $_

    }

    finally {

    $ErrorActionPreference = $PreferenceErrorAction

    }

  • @Walid Toumi, great addition. Thank you your comment.