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
  • <p>hi,</p> <p>Thanks Ed, here is also:</p> <p>c. $LastExitCode</p> <p>PS II&gt; replace</p> <p>PS II&gt; $LastExitCode</p> <p>11</p> <p>d. ErrorVariable parameter</p> <p>PS II&gt; get-item 1:\xoo -ErrorAction 0 -ErrorVariable foo</p> <p>PS II&gt; if($foo) { write-error &quot;error !!&quot; }</p> <p>e. try catch finally</p> <p>PS II&gt; try {</p> <p> &nbsp;$PreferenceErrorAction=$ErrorActionPreference</p> <p> &nbsp;$ErrorActionPreference = &#39;stop&#39;</p> <p> &nbsp;command....</p> <p>}</p> <p>catch {</p> <p> &nbsp;$_</p> <p>}</p> <p>finally {</p> <p> $ErrorActionPreference = $PreferenceErrorAction</p> <p>}</p>

  • <p>@Walid Toumi, great addition. Thank you your comment.</p>