PowerTip: Check to See if a Command Completes Properly

PowerTip: Check to See if a Command Completes Properly

Rate This
  • Comments 2

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.

Leave a Comment
  • Please add 2 and 5 and type the answer here:
  • Post
  • 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.

Page 1 of 1 (2 items)