Scheduled Tasks & PowerShell

Triggering Script from GitHub

This post was mostly created for myself to help remember tricks I use in creating scheduled tasks with PowerShell. I find it handy when developing thing in my lab to keep the script in GitHub, and call it remotely. You can also easily modify the script to copy the script local or embed the script and build it as part of your Scheduled Task Deployment.
Script on GitHub: garytown/Create-ScheduledTask-TriggerPSScript.ps1

Related:

PowerShell Command I want the Scheduled Task to run:

$PSCommand = 'iex (irm https://raw.githubusercontent.com/gwblok/garytown/master/hardware/HP/Docks/Set-HPDockHistory_WMI.ps1)'

That is the command to run the powershell script located at that location in GitHub

Action

#Action to Trigger:
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NoProfile -WindowStyle Hidden -ep bypass -command `"$PSCommand`""

This is the EXE that the Scheduled Task will all (Powershell.exe), and the arguments to go alone with it.

Trigger(s)

#Trigger on Event: 
$CIMTriggerClass = Get-CimClass -ClassName MSFT_TaskEventTrigger -Namespace Root/Microsoft/Windows/TaskScheduler:MSFT_TaskEventTrigger
$Trigger = New-CimInstance -CimClass $CIMTriggerClass -ClientOnly
$Trigger.Subscription = @"
<QueryList><Query Id="0" Path="System"><Select Path="System">*[System[Provider[@Name='nhi'] and EventID=9008]]</Select></Query></QueryList>
"@
$Trigger.Delay = 'PT1M'
$Trigger.Enabled = $True 

That will create a trigger based on event [ID 9008], create a time delay of 1 minute.

#Trigger daily as well
$Trigger2 = New-ScheduledTaskTrigger -Daily -At '1:15 PM' -RandomDelay "02:00" -DaysInterval 1

#Combine Triggers
$triggers = @()
$triggers += $Trigger
$triggers += $Trigger2

I also wanted to have the task trigger daily at 1:15PM with random delay of 2 hours. I then combine both triggers into 1 variable.

Principal (Run As)

#Run as System
$Prin = New-ScheduledTaskPrincipal -UserId "SYSTEM" -RunLevel Highest

This will set the task to run as SYSTEM and to Run with highest privileges.
Note, this can also be accomplished by using -User ‘SYSTEM’ when registering the task.

Timeout & Other Settings

#Stop Task if runs more than 60 minutes
$Timeout = (New-TimeSpan -Minutes 60)

I create a time out variable of 60 minutes. To do this, use “New-TimeSpan”, this is used for the New-ScheduledTaskSettingsSet command.

#Other Settings on the Task:
$settings = New-ScheduledTaskSettingsSet -RunOnlyIfNetworkAvailable -StartWhenAvailable -DontStopIfGoingOnBatteries -ExecutionTimeLimit $Timeout

These will check other boxes in the settings area. I only wanted to run it when on Network, Run if available, and don’t care about being on Battery, and then set the Timeout I created above.

Create & Register Scheduled Task

#Set Name of Task
[String]$TaskName = "Run PowerShell Script from GitHub Daily & on Event"

#Create the Task
$task = New-ScheduledTask -Action $action -principal $Prin -Trigger $triggers -Settings $settings

#Register Task with Windows
Register-ScheduledTask -TaskName $TaskName -InputObject $task -Force -ErrorAction SilentlyContinue

GARYTOWN.COM

2 thoughts on “Scheduled Tasks & PowerShell”

  1. Nice article. This will help me migrate my tasks scripts GH instead of having them on a share drive where other users can hose them up. I have to use this with a private repo, but the added benefit is that private repos have a token appended to the end of the raw content url. This token is different with each commit, giving me basically multiple versions in production so I’m breaking it on an older os server.

    Great help!

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.