PurpleScreen blog about open source

PowerShell scheduled job output redirection

Scheduling the script execution is rather common task. You might know that it’s possible to manage scheduled tasks in PowerShell with built-in ScheduledTask module cmdlets. To keep track whether the task run successfully or not it’s quite useful to redirect the output of the script to a file. PowerShell allows output redirection for all stream types (standard/error/warning/etc), see TechNet about_Redirection help topic.

To be able to run your scripts with -Verbose option you should leverage Advanced_Functions syntax (see another Core About topic). Just add couple of strings to the beginning of the script:

[CmdletBinding()]
param()

and use Write-Verbose cmdlet throughout the script where chatty output is needed. At first glance it seems to be an easy task to combine all the mentioned together, but in fact I saw lots of questions across the web where people struggled to make it work. Indeed, it took much effort before I succeeded. I’ve tested many different configuration and most of them didn’t work for me too. That’s what I came up with and it worked for me:

Register-ScheduledJob .. -ScriptBlock { C:\Scheduled.ps1 -Verbose *> 'C:\Scheduled.log' }