14

I am trying to run a few command prompt commands like schtasks within a PowerShell script. I would like to know how to handle errors thrown by the command in PowerShell.

I tried:

  • & cmd.exe /c 'schtasks /Query /TN xx || echo ERROR'
  • & cmd.exe /c 'ping.exe 122.1.1.1 && exit 0 || exit 1'
  • Invoke-Expression -Command:$command

I'm unable to run these commands and ignore or catch exception in a try..catch block of the PowerShell script. I know there are libraries but I'm limited to PowerShell v2.0.

3
  • Check $LASTEXITCODE after each invocation of cmd.exe - a nonzero value indicates that the command failed. Normally you can just let the command itself report its exit code, without the need for a || clause. However, if you do use one, be sure that it ends with exit 1 (or a different nonzero exit code); in your first command, because you execute echo (as the one and only command) in the || clause, the overall exit code will mistakenly be 0. Commented Jan 12, 2016 at 23:17
  • yes, but if the command throws an error, the powershell script also displays that error, i want to avoid seeing that error message. Commented Jan 12, 2016 at 23:21
  • To suppress the command's stderr output, append 2>NUL directly to the command in question (inside the single quotes); e.g. 'schtasks /Query /TN xx 2>NUL'. To suppress stdout output also, add >NUL. Commented Jan 12, 2016 at 23:23

1 Answer 1

21

External commands usually set a non-zero exit code if they're terminating with an error, so you could check if the automatic variable $LASTEXITCODE has a non-zero value:

& cmd /c 'schtasks /Query /TN xx'
if ($LASTEXITCODE -ne 0) {
  'an error occurred'
}

Note, however, that there are some programs that use non-zero exit codes for non-error information, (e.g. robocopy, which uses the exit codes below 8 for status information, or choice, which uses the exit code to indicate the chosen option).

Error messages of the external command can be suppressed by redirecting the error output stream, either in CMD:

& cmd /c 'schtasks /Query /TN xx 2>nul'

or in PowerShell:

& cmd /c 'schtasks /Query /TN xx' 2> $null
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.