Author: @OperativeThunny This is part of a series of snippits I am uploading on my github gists for internet clout. License for this collection of snippits is AGPL. I am open to relicensing if AGPL is too restrictive, just contact me!
Copyright (C) 2023 @OperativeThunny
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/.
To make a new scheduled task in PowerShell (pwsh) you need to gather together a set of objects defining the scheduled task, as can be seen in the windows GUI (winkey + r + taskschd.msc + enter btw), then you supply those objects to the new-scheduledtask commandlet (cmdlet) and the register-scheduledtask cmdlet.
- New-ScheduledTaskAction
- New-ScheduledTaskTrigger
- New-ScheduledTaskSettingsSet
- New-ScheduledTaskPrincipal
- New-ScheduledTask
- Register-ScheduledTask
$sta = New-ScheduledTaskAction `
-Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" `
-Argument "-noprof -ex Bypass -file C:\Users\othunny\StartupScripts\aidle.ps1" `
-WorkingDirectory "C:\Users\othunny\"
$stt = New-ScheduledTaskTrigger `
-AtLogOn `
-RandomDelay ([System.TimeSpan]::FromMinutes(59)) `
-User "DOMAIN\othunny"
$sts = New-ScheduledTaskSettingsSet `
-Compatibility ([Microsoft.PowerShell.Cmdletization.GeneratedTypes.ScheduledTask.CompatibilityEnum]::Win8) `
-ExecutionTimeLimit ([timespan]::FromHours(1)) `
-MultipleInstances ([Microsoft.PowerShell.Cmdletization.GeneratedTypes.ScheduledTask.MultipleInstancesEnum]::IgnoreNew)
$stp = New-ScheduledTaskPrincipal `
-UserId "DOMAIN\othunny"
$st = New-ScheduledTask `
-Action $sta `
-Settings $sts `
-Principal $stp `
-Trigger $stt `
-Description "This is a scheduled task created from the powershell cmdlet interface"
$st | Register-ScheduledTask `
-TaskName "Pwsh_taskschd_task" `
-TaskPath "\"