Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save OperativeThunny/0e1c2abd77324837f411828ee329d6dd to your computer and use it in GitHub Desktop.
Save OperativeThunny/0e1c2abd77324837f411828ee329d6dd to your computer and use it in GitHub Desktop.
This gist shows how to make a new scheduled task with powershell.

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/.

Making a new scheduled task from powershell:

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.

Order of cmdlet execution

  1. New-ScheduledTaskAction
  2. New-ScheduledTaskTrigger
  3. New-ScheduledTaskSettingsSet
  4. New-ScheduledTaskPrincipal
  5. New-ScheduledTask
  6. Register-ScheduledTask

Example:

$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 "\"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment