PowerTip: Check to See if a Command Completes Properly

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.

Comments (2)

  1. Walid Toumi says:


    Thanks Ed, here is also:

    c. $LastExitCode

    PS II> replace

    PS II> $LastExitCode


    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 {


     $ErrorActionPreference = 'stop'



    catch {



    finally {

    $ErrorActionPreference = $PreferenceErrorAction


  2. Ed Wilson says:

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