Run Powershell script as Windows Scheduled Task and reflect script result to task result

When you need to execute a powershell script through Windows Task Scheduler, follow the steps below

- How to create Scheduled Task Action to execute Powershell script

  • Action Type : Start Program
  • Program/Script: Powershell -file "?filePath?" -ExecutionPolicy Bypass
    Replace ?filePath? with your script path.


- How to reflect script return value to Scheduled Task result value

The following code from your powershell script won't change the result of the task result. Task result will be gathered from PowerShell program and that will be success all the time.


if (...)
{
    return 0 
}
else {
    return 1
}

Instead of using return command, use [Environment]::Exit command to change the task result.

if (...)
{
    [Environment]::Exit(0) 
}
else {
    [Environment]::Exit(1)
}

Note: 
Major Task Result codes
0x0: The operation completed successfully.
0x1: An incorrect function was called or an unknown function was called.
0xa: The environment is incorrect.

Comments