PowerShell Script Scheduler / Automator

This little script is designed for those occasions where you want to schedule / automate the running of a PowerShell script, but are stymied by Enterprise restrictions preventing you from setting up standard Windows scheduled tasks. This PowerShell script will schedule on a daily basis (specific minute - but not exactly on the minute - of a specific hour of specific days of the week.) It’s simple and solves a problem. It does require the user running the script (and whatever script the script needs to run), to remain logged in (and I’d recommend logged into the console session); and after a reboot, the user will need to be logged back in again and the scheduler re-started (perhaps a simple batch file to kick it of.)

The code (formatted for blogger) is below. As always, copy and paste into a text editor and save as say “PS-Script-Scheduler.ps1”.

###########################################
# PowerShell Script Scheduler / Automator #
############################################################
# + Include PS script to be scheduled and all switches.    #
# + Mandatory switches: -Script, -Minute, -Hour, -Days     #
# + Do not abbreviate days of the week!                    #
# + If you don't specify -Runs or set it to 0,             #
#   the program runs infinitely until terminated.          #
# + Usage example:                                         #
# .\PS-Script-Scheduler.ps1 -Script ".\script.ps1 -Sw1"    #
#     -Minute 0 -Hour 6 -Days Tuesday,Friday               #
############################################################

Param(
[Parameter(Mandatory=$true)][String]$Script,
[Parameter(Mandatory=$true)][String]$Minute,
[Parameter(Mandatory=$true)][String]$Hour,
[Parameter(Mandatory=$true)][System.Array]$Days,
[Int]$Runs
)

[Int]$RunsCount = 0
[Boolean]$Triggered = $FALSE
while($TRUE){
# The Script Scheduler checks time every 60 seconds
Start-Sleep 60
$Date = Get-Date
If(!$Triggered){
If($Date.Minute -ge [Int]$Minute){
If($Date.Hour -eq [Int]$Hour){
Foreach($Day in $Days){
If($Date.Dayofweek -eq $Day){
Invoke-Expression $Script
$Triggered = $TRUE
$RunsCount++
"TRIGGERED at $Date"
"Invoked expression:"
"$Script"
}
}
}
}
}
If($Triggered){
If($Date.Hour -ne $Hour){
# Reset the trigger
$Triggered = $FALSE
}
}
If($Runs){
If($RunsCount -ge $Runs){ EXIT }
}
}

Comments