Scheduled task runs with exit code 0, but powershell script is not always executed

Solution 1:

I think the exit code task scheduler is reporting is for running powershell.exe not your script.

Try changing it to this:

-ExecutionPolicy Bypass –NoProfile –Command "& {C:\ProgramData\ORGNAME\scripts\SetDNS.ps1; exit $LastExitCode}" > C:\ProgramData\ORGNAME\scripts\SetDNS.log

$LastExitCode has the exit code of the your script, you have to bubble it up one level to the task scheduler.

It would also be a good idea to add some error handling to your script and use Exit statements to set the actual exit codes.

Solution 2:

Remove the -Command from your script parameters and instead use -File . Command is meant to be used when you are entering powershell commands but you have a script file instead.

Details here