I recently was working with a script that had very specific requirements:
- The script had to run as a scheduled task
- The scheduled task itself had to be created using PowerShell
- The script had to run once the servers started up
- The task had to repeat every 10 minutes for 1 day
Creating a scheduled task is pretty straight forward and is well documented here. But I quickly discovered that creating a scheduled task with the specific parameters that were needed is not as simple as it might seem. In this blog post I am going to show you how to create a scheduled task using Powershell, call a PowerShell script using that scheduled task, and configure parameters of the scheduled task that are not provided through the PowerShell Scheduled Task cmdlets. So lets go ahead and create an example scheduled task that meets all of the requirements.
Create a Sample Script
First lets create a very basic sample script that the scheduled task will run. The following code simply records the date and time and outputs it to a log file in the same folder as the script.
#Stores Script's Current Location
$sCurrDir = $myinvocation.mycommand.path
$sCurrDir = $sCurrDir.Replace("\" + $myinvocation.MyCommand, "")
#Log Output Path
$OutputPath = "$sCurrDir\SampleScheduledTask.log"
#Outputs to log file
function Write-Log{
param(
[string]$OutputPath
)
#Stores Date / Time
$Date = $TimeStamp = (get-date).toshortdatestring(); $Time = (get-date).tolongtimestring()
#Creates Output Message
$Message = "I ran on $Date at $Time"
#Writes Output Message to log file
$Message | Add-Content $OutputPath
}
#Calls Log Function
Write-Log -OutputPath $OutputPath
Some astute