Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle command prompt error within PowerShell script

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.

like image 940
semantic_c0d3r Avatar asked Jan 12 '16 23:01

semantic_c0d3r


1 Answers

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
like image 135
Ansgar Wiechers Avatar answered Sep 30 '22 19:09

Ansgar Wiechers