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:$commandI'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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With