Calling PowerShell scripts from Task Scheduler

Recently, I spent some time getting a PowerShell script run scheduled in Windows Task Scheduler. In this article I describe the most important findings about creating the schedule, calling the script and capturing its output.

Let's assume that you know how to manually create tasks in Task Scheduler. To call your script from the task, add an Action that starts program powershell.exe with arguments -File "C:\My Scripts\Script.ps1" -ScriptParam "parameter 1". Everything that goes after the file name is passed as parameters to your script. You can enclose the parameters in quotation marks if they contain spaces.

That's it, you're set. Or at least until you want to check whether the script works. Where does the output of the scheduled script goes? The answer is, nowhere. There is no console for scheduled tasks. At least not for those scheduled to run whether user is logged on or not. The only way how to get to the output of such script, is to capture it into a file and read it from there. It is possible to use output redirection like Script.ps1 > output.txt but using the output pipeline of a script for logging purposes is, first, not quite right and, second, for more complex scripts much more cumbersome than one would expect. I recommend to pass the name of the log file as an optional parameter to the script. The method for logging then decides whether to write on the console or to a file:

function Log($msg) {  
    if(($ConsoleOutputFile -eq $null) -or ($ConsoleOutputFile -eq "")) {
        Write-Host $msg
    } else {
        if(-not (Test-Path $ConsoleOutputFile)) {
            New-Item $ConsoleOutputFile -ItemType file -Force #creates the file including any necessary directories
        }
        Add-Content $ConsoleOutputFile $msg
    }
} 

When a script is called by the Task Scheduler, its working directory is set to C:\Windows\System32. Use absolute path of the log file as a parameter and don't rely on relative paths in the script.

In the next article I am going to show how to schedule the script in Task Scheduler programmatically.