On this page

PowerShell Scheduled Tasks

Updated on June 19, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Scheduled tasks are the foundation of automation in Windows, enabling scripts and programs to run on a defined schedule or in response to system events. PowerShell's ScheduledTasks module provides a complete, object-oriented interface to the Windows Task Scheduler service, allowing administrators to create, query, modify, and remove tasks programmatically across local and remote systems. Every scheduled task is built from four independent components—triggers, actions, principals, and settings—which are constructed separately and combined at registration. Understanding this architecture and following security best practices, particularly the principle of least privilege and proper credential management, is essential for building reliable and secure automation.


Task Scheduler Architecture​

Every scheduled task is built from four independent components that are constructed separately and then combined at registration:

Understanding this separation is essential because PowerShell constructs each component as a distinct object. You build them individually and combine them only when calling Register-ScheduledTask.


The ScheduledTasks Module​

The ScheduledTasks module ships with Windows and requires no installation. To verify the module is available and see all cmdlets:


Get-Command -Module ScheduledTasks

The complete set of cmdlets includes:

CmdletPurposeNew-ScheduledTaskActionCreates a task action objectNew-ScheduledTaskTriggerCreates a task trigger objectNew-ScheduledTaskPrincipalCreates a task principal (security context) objectNew-ScheduledTaskSettingsSetCreates a task settings objectNew-ScheduledTaskCombines components into a task definition without registering itRegister-ScheduledTaskRegisters a task definition with the Task Scheduler serviceGet-ScheduledTaskGets the task definition of registered tasksGet-ScheduledTaskInfoGets runtime state: last run time, last result, next run timeSet-ScheduledTaskModifies a registered task definitionStart-ScheduledTaskStarts a task asynchronously, regardless of its triggerStop-ScheduledTaskStops all running instances of a taskEnable-ScheduledTaskEnables a disabled taskDisable-ScheduledTaskDisables a task without removing itExport-ScheduledTaskExports a task definition as an XML stringUnregister-ScheduledTaskPermanently removes a registered task


Inspecting Existing Scheduled Tasks​

Before creating or modifying tasks, understanding what already exists on the system prevents conflicts and overwrites.

List All Registered Tasks​


Get-ScheduledTask

This lists all available scheduled tasks, regardless of whether they are enabled or disabled.

Filter by State​


# All currently ready (enabled) tasks

Get-ScheduledTask | Where-Object State -eq 'Ready'



# All disabled tasks

Get-ScheduledTask | Where-Object State -eq 'Disabled'

Query a Specific Task​


Get-ScheduledTask -TaskName 'DailyBackup'

Query All Tasks in a Folder​

Using -TaskPath organizes tasks into folders — a practice essential in environments with many tasks:


Get-ScheduledTask -TaskPath '\Administration\'

Get Runtime Information​

Get-ScheduledTask retrieves the task definition — what the task is configured to do. Get-ScheduledTaskInfo retrieves the runtime state — what the task actually did the last time it ran:


Get-ScheduledTaskInfo -TaskName 'DailyBackup'

The output includes:

Common LastTaskResult Codes​

CodeMeaning0 (0x0)Success1 (0x1)General failure — check the script itself267009 (0x41301)Task is currently running267011 (0x41303)Task has not yet run2147750687 (0x8004131F)An instance of the task is already running2147943645 (0x8007052D)Logon failure — credentials are incorrect or expired


Creating a Scheduled Task​

Task creation follows a consistent four-step pattern: define the action, define the trigger, define the principal, define the settings, then register.

Step 1 — Define the Action​

The action specifies what the task executes. When running a PowerShell script, always pass -ExecutionPolicy Bypass to prevent execution policy restrictions from silently blocking the script in a non-interactive context:


$action = New-ScheduledTaskAction `

    -Execute 'powershell.exe' `

    -Argument '-ExecutionPolicy Bypass -NonInteractive -File "C:\Scripts\Backup.ps1"'

Code explanation: -Execute specifies the program to run (PowerShell). -Argument provides the command-line arguments. -ExecutionPolicy Bypass overrides the execution policy for this script. -NonInteractive prevents prompts. The script path is quoted to handle spaces in the file path.

Script paths with spaces: if the script path contains spaces, the inner quotes are mandatory. Omitting them causes the task to fail silently — the task reports "success" but the script never runs because the path is parsed incorrectly.

For PowerShell 7 (pwsh.exe), use the full path to the executable:


$action = New-ScheduledTaskAction `

    -Execute 'C:\Program Files\PowerShell\7\pwsh.exe' `

    -Argument '-ExecutionPolicy Bypass -NonInteractive -File "C:\Scripts\Backup.ps1"'

Step 2 — Define the Trigger​

Triggers control when the task fires. A task can have up to 48 triggers.

Daily at a fixed time:


$trigger = New-ScheduledTaskTrigger -Daily -At '03:00'

Weekly on specific days:


$trigger = New-ScheduledTaskTrigger -Weekly -WeeksInterval 1 -DaysOfWeek Monday, Wednesday, Friday -At '07:00'

At system startup:


$trigger = New-ScheduledTaskTrigger -AtStartup

At user logon:


$trigger = New-ScheduledTaskTrigger -AtLogOn

Repeating on an interval — run once, then repeat every 30 minutes indefinitely:


$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 30)

Multiple triggers on the same task:


$trigger1 = New-ScheduledTaskTrigger -AtStartup

$trigger2 = New-ScheduledTaskTrigger -Daily -At '03:00'

# Both triggers are passed as an array at registration

Step 3 — Define the Principal​

The principal specifies the security context the task runs under. This is the most security-sensitive component.

Run as SYSTEM (most common for unattended administrative tasks):


$principal = New-ScheduledTaskPrincipal `

    -UserId 'NT AUTHORITY\SYSTEM' `

    -LogonType ServiceAccount `

    -RunLevel Highest

SYSTEM has full local administrative access. Use it for tasks that need unrestricted local access, do not need network credentials, and must run whether any user is logged on or not.

Run as a specific service account (least privilege approach):


$principal = New-ScheduledTaskPrincipal `

    -UserId 'DOMAIN\svc-backup' `

    -LogonType Password `

    -RunLevel Highest

Run as the currently logged-on user (interactive tasks):


$principal = New-ScheduledTaskPrincipal `

    -GroupId 'BUILTIN\Users' `

    -RunLevel Limited

-RunLevel Highest corresponds to the "Run with highest privileges" checkbox in the Task Scheduler GUI. Use it only when the task genuinely requires elevation.

Step 4 — Define the Settings​

Settings control operational behaviour:


$settings = New-ScheduledTaskSettingsSet `

    -ExecutionTimeLimit (New-TimeSpan -Hours 1) `    # Kill the task after 1 hour

    -MultipleInstances IgnoreNew `                    # Skip if task is already running

    -RestartCount 3 `                                 # Retry up to 3 times on failure

    -RestartInterval (New-TimeSpan -Minutes 5) `      # Wait 5 minutes between retries

    -StartWhenAvailable `                             # Run as soon as possible if a scheduled start was missed

    -AllowStartIfOnBatteries `                        # Allow on laptops running on battery

    -DontStopIfGoingOnBatteries                       # Do not stop if power switches to battery mid-run

-MultipleInstances accepts: Queue (queue the new instance), Parallel (run both), IgnoreNew (discard the new instance), or StopExisting (stop the running instance and start fresh).

Step 5 — Register the Task​

Combine all components and register the task:


Register-ScheduledTask `

    -TaskName 'DailyBackup' `

    -TaskPath '\Administration\' `

    -Action $action `

    -Trigger $trigger `

    -Principal $principal `

    -Settings $settings `

    -Description 'Runs the daily backup script at 3 AM.' `

    -Force

-Force overwrites an existing task with the same name without prompting. Omit it in scripts where an accidental overwrite would be destructive.


Credentials and Security Context​

Running as SYSTEM (Preferred for Unattended Tasks)​

Tasks that run as SYSTEM do not require a stored password. They start whether or not a user is logged on, have full local privileges, and are immune to password expiration:


Register-ScheduledTask `

    -TaskName 'SystemMaintenance' `

    -TaskPath '\Administration\' `

    -Action $action `

    -Trigger $trigger `

    -Principal (New-ScheduledTaskPrincipal -UserId 'NT AUTHORITY\SYSTEM' -LogonType ServiceAccount -RunLevel Highest) `

    -Settings $settings

Running as a Named Account​

When a task needs to access network resources — file shares, databases, APIs — it must run as a domain account with the appropriate permissions, because SYSTEM has no network credentials:


Register-ScheduledTask `

    -TaskName 'NetworkBackup' `

    -TaskPath '\Administration\' `

    -Action $action `

    -Trigger $trigger `

    -Principal (New-ScheduledTaskPrincipal -UserId 'DOMAIN\svc-backup' -LogonType Password -RunLevel Highest) `

    -Settings $settings `

    -Password 'AccountPassword'

Security note: passing a password as a plaintext string in a script is a risk. In production, use Group Managed Service Accounts (gMSA) to avoid password management entirely, read the password from a secrets manager, or use SYSTEM to avoid passwords altogether. Never store plaintext credentials in script files committed to source control.

The Principle of Least Privilege​

A task only needs the permissions required to complete its specific function. Avoid running all tasks as SYSTEM or as a Domain Admin. Create dedicated service accounts with only the permissions the task requires. This limits the blast radius if a script is compromised or misbehaves.


Modifying Existing Tasks​

Set-ScheduledTask modifies a registered task definition. Changes take effect on the next run.

Update the Trigger​


$newTrigger = New-ScheduledTaskTrigger -Daily -At '02:00'

Set-ScheduledTask -TaskName 'DailyBackup' -TaskPath '\Administration\' -Trigger $newTrigger

Update the Action​


$newAction = New-ScheduledTaskAction `

    -Execute 'powershell.exe' `

    -Argument '-ExecutionPolicy Bypass -NonInteractive -File "C:\Scripts\BackupV2.ps1"'

Set-ScheduledTask -TaskName 'DailyBackup' -TaskPath '\Administration\' -Action $newAction

Update the Principal (Change Run-As Account)​


$newPrincipal = New-ScheduledTaskPrincipal -UserId 'NT AUTHORITY\SYSTEM' -LogonType ServiceAccount -RunLevel Highest

Set-ScheduledTask -TaskName 'DailyBackup' -TaskPath '\Administration\' -Principal $newPrincipal

Enabling, Disabling, Starting, and Stopping Tasks​

Enable a Disabled Task​


Enable-ScheduledTask -TaskName 'DailyBackup' -TaskPath '\Administration\'

Disable a Task Without Removing It​


Disable-ScheduledTask -TaskName 'DailyBackup' -TaskPath '\Administration\'

Disabling is the correct approach when a task must be temporarily suspended. It preserves the full definition and all configuration.

Start a Task Immediately​

Start-ScheduledTask launches the task asynchronously — it returns immediately without waiting for the task to complete:


Start-ScheduledTask -TaskName 'DailyBackup' -TaskPath '\Administration\'

To wait for a task to finish before continuing:


Start-ScheduledTask -TaskName 'DailyBackup' -TaskPath '\Administration\'



# Poll until the task is no longer running

do {

    Start-Sleep -Seconds 5

    $state = (Get-ScheduledTask -TaskName 'DailyBackup').State

} while ($state -eq 'Running')



$result = (Get-ScheduledTaskInfo -TaskName 'DailyBackup').LastTaskResult

Write-Output "Task completed with exit code: $result"

Stop a Running Task​


Stop-ScheduledTask -TaskName 'DailyBackup' -TaskPath '\Administration\'

Removing Tasks​


Unregister-ScheduledTask -TaskName 'DailyBackup' -TaskPath '\Administration\' -Confirm:$false

-Confirm:$false suppresses the interactive confirmation prompt. Before removing tasks in production, export the definition first:


Export-ScheduledTask -TaskName 'DailyBackup' -TaskPath '\Administration\' |

    Out-File -FilePath 'C:\Backups\Tasks\DailyBackup.xml' -Encoding UTF8

The exported XML can be used to recreate the task on any Windows system using Register-ScheduledTask -Xml.


Remote Task Management​

All ScheduledTasks cmdlets support remote management through CIM sessions. Establish a CIM session first, then pass it to any cmdlet:


$session = New-CimSession -ComputerName 'Server01'



# List all tasks on the remote computer

Get-ScheduledTask -CimSession $session



# Register a task on the remote computer

Register-ScheduledTask `

    -TaskName 'DailyBackup' `

    -TaskPath '\Administration\' `

    -Action $action `

    -Trigger $trigger `

    -Principal $principal `

    -Settings $settings `

    -CimSession $session



# Clean up the session when done

Remove-CimSession -CimSession $session

To manage tasks across multiple computers simultaneously:


$servers = 'Server01', 'Server02', 'Server03'

$sessions = New-CimSession -ComputerName $servers



Get-ScheduledTask -CimSession $sessions | Select-Object TaskName, State, PSComputerName

Practical Administrative Scenarios​

Audit Failed Tasks Across the System​


Get-ScheduledTask | ForEach-Object {

    $info = Get-ScheduledTaskInfo -TaskName $_.TaskName -TaskPath $_.TaskPath

    if ($info.LastTaskResult -ne 0 -and $info.LastRunTime -ne $null) {

        [PSCustomObject]@{

            TaskName       = $_.TaskName

            TaskPath       = $_.TaskPath

            LastRunTime    = $info.LastRunTime

            ResultCode     = '0x{0:X}' -f $info.LastTaskResult

            NextRunTime    = $info.NextRunTime

        }

    }

} | Sort-Object LastRunTime | Format-Table -AutoSize

List the Run-As Account for Every Task​

A common auditing requirement is knowing which account each task runs under:


Get-ScheduledTask | ForEach-Object {

    [PSCustomObject]@{

        TaskName  = $_.TaskName

        TaskPath  = $_.TaskPath

        RunAsUser = $_.Principal.UserId

        RunLevel  = $_.Principal.RunLevel

        State     = $_.State

    }

} | Sort-Object RunAsUser | Format-Table -AutoSize

Repeating Cleanup Task with a Random Startup Delay​

A random delay prevents all machines in a fleet from hammering a resource simultaneously at the same scheduled second:


$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours 1)

$trigger.Delay = 'PT{0}M' -f (Get-Random -Minimum 1 -Maximum 10)   # 1–9 minute random delay



$action = New-ScheduledTaskAction `

    -Execute 'powershell.exe' `

    -Argument '-ExecutionPolicy Bypass -NonInteractive -File "C:\Scripts\Cleanup.ps1"'



$principal = New-ScheduledTaskPrincipal -UserId 'NT AUTHORITY\SYSTEM' -LogonType ServiceAccount -RunLevel Highest



$settings = New-ScheduledTaskSettingsSet `

    -ExecutionTimeLimit (New-TimeSpan -Minutes 30) `

    -MultipleInstances IgnoreNew



Register-ScheduledTask `

    -TaskName 'HourlyCleanup' `

    -TaskPath '\Maintenance\' `

    -Action $action `

    -Trigger $trigger `

    -Principal $principal `

    -Settings $settings `

    -Force

Deploy a Task to Multiple Remote Servers​


# Export the task definition from the reference machine

$xml = Export-ScheduledTask -TaskName 'DailyBackup' -TaskPath '\Administration\'



# Register it on all target servers

$servers = 'Server01', 'Server02', 'Server03'



foreach ($server in $servers) {

    $session = New-CimSession -ComputerName $server

    Register-ScheduledTask `

        -TaskName 'DailyBackup' `

        -TaskPath '\Administration\' `

        -Xml $xml `

        -CimSession $session `

        -Force

    Remove-CimSession -CimSession $session

    Write-Output "Deployed to $server"

}

Redirecting Script Output for Troubleshooting​

Scheduled tasks run in a non-interactive session with no visible console. Redirect output to a log file in the script itself:


# At the top of C:\Scripts\Backup.ps1

$logPath = "C:\Logs\Backup_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"

Start-Transcript -Path $logPath -Append



# ... script logic ...



Stop-Transcript

Alternatively, redirect both stdout and stderr in the action argument:


$action = New-ScheduledTaskAction `

    -Execute 'powershell.exe' `

    -Argument '-ExecutionPolicy Bypass -NonInteractive -File "C:\Scripts\Backup.ps1" *>> "C:\Logs\Backup.log"'

Security Considerations and Best Practices​

Use SYSTEM only when necessary. SYSTEM has unrestricted local access. For most administrative tasks, a dedicated service account with only the required permissions is safer.

Never store plaintext passwords in script files. Use Group Managed Service Accounts (gMSA) to avoid password management entirely, use Windows DPAPI via Export-Clixml/Import-Clixml, or use SYSTEM to avoid passwords.

Always use -ExecutionPolicy Bypass in the action argument. Execution policy restrictions apply in the non-interactive context of scheduled tasks. Without this flag, a script that works interactively will fail silently when run by the scheduler.

Quote script paths that may contain spaces. C:\Program Files\... silently breaks task execution when not properly quoted in the -Argument string.

Organise tasks into folders with -TaskPath. All tasks in the root path \ create a cluttered, unmanageable library. Use meaningful paths like \Administration\, \Maintenance\, \Monitoring\ to group related tasks.

Export task definitions before removing them. Export-ScheduledTask produces an XML string that can recreate the task exactly.

Audit task run-as accounts regularly. Identify tasks running under Domain Admin or shared credentials — both are security risks that should be remediated to dedicated service accounts.

Add logging to every script run by a scheduled task. Because tasks run silently, Start-Transcript or file-based logging is the only way to diagnose failures after the fact.

Test scripts in a safe environment first before deploying to production.


Cmdlet Quick Reference​

TaskCmdletList all tasksGet-ScheduledTaskGet runtime stateGet-ScheduledTaskInfoCreate actionNew-ScheduledTaskActionCreate triggerNew-ScheduledTaskTriggerCreate principalNew-ScheduledTaskPrincipalCreate settingsNew-ScheduledTaskSettingsSetRegister taskRegister-ScheduledTaskModify taskSet-ScheduledTaskEnable taskEnable-ScheduledTaskDisable taskDisable-ScheduledTaskRun immediatelyStart-ScheduledTaskStop running taskStop-ScheduledTaskExport to XMLExport-ScheduledTaskDelete taskUnregister-ScheduledTask

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Event Logs

Next

Local Users and Groups