Last active
April 8, 2022 13:43
-
-
Save mtboren/81eaf20dca386bba10b4d5d03562f8c4 to your computer and use it in GitHub Desktop.
Register Scheduled Task to use PowerShell 7 to run ps1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## some things for making and registering a scheduled task via PowerShell, with the task Action running via PowerShell 7 at run time | |
## creds for the new scheduled task | |
$credForSchedTask = Get-Credential coolguy@domain.com | |
## params for making a new scheduled task object in the PowerShell session | |
$hshParamForNewScheduledTask = @{ | |
Action = New-ScheduledTaskAction -Execute "C:\Program Files\PowerShell\7\pwsh.exe" -Argument "-File E:\scripts\scheduled\Invoke-MyCoolThing.ps1" -WorkingDirectory "C:\temp" | |
Description = "My important task to do all the things" | |
## additional settings | |
Settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Hours 12) -MultipleInstances IgnoreNew | |
## start at given time, on given days of the week every week, with a random delay | |
# Trigger = New-ScheduledTaskTrigger -At 5am -Weekly -DaysOfWeek ([DayOfWeek[]]("Monday,Tuesday,Wednesday,Thursday,Friday".Split(","))) -RandomDelay (New-TimeSpan -Minutes 2) | |
## Or, every day | |
Trigger = New-ScheduledTaskTrigger -Daily -At 3am -RandomDelay (New-TimeSpan -Minutes 1) | |
Verbose = $true | |
OutVariable = "oNewScheduledTask" | |
} ## end hsh | |
## params for registering the new scheduled task object from the PowerShell session into the Task Scheduler "system" | |
$hshParamForRegisterSchedTask = @{ | |
InputObject = New-ScheduledTask @hshParamForNewScheduledTask | |
Password = $credForSchedTask.GetNetworkCredential().Password | |
TaskName = "My_test_task" | |
## per help: "Specifies the path for a scheduled task in Task Scheduler namespace. You can use \ for the root folder" | |
TaskPath = "\" | |
User = $credForSchedTask.UserName | |
Verbose = $true | |
} ## end hsh | |
## actually register the scheduled task in Windows | |
Register-ScheduledTask @hshParamForRegisterSchedTask |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment