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.
$LASTEXITCODEafter each invocation ofcmd.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 withexit 1(or a different nonzero exit code); in your first command, because you executeecho(as the one and only command) in the||clause, the overall exit code will mistakenly be0.2>NULdirectly to the command in question (inside the single quotes); e.g.'schtasks /Query /TN xx 2>NUL'. To suppress stdout output also, add>NUL.