Powershell - create scheduled task in Windows Task Scheduler - part 3
Published on: 27th Dec 2019
Updated on: 23th Jul 2025
Overview
This is the last part of the managing Windows Schedule Task using Powershell which explains how to run a task in an user context.
Explanation
This is the last part of Task Scheduler - security context which is created using New-ScheduledTaskPrincipal
. Usually, we are using S4U logon type for any server scheduled task + Highest Run Level.
S4U details as per MS documentation:
Use an existing interactive token to run a task. The user must log on using a service for user (S4U) logon. When an S4U logon is used, no password is stored by the system and there is no access to either the network or encrypted files.
You can find more information in this page:
For any user ID that you specified to run the scheduled task, it requires "Log on as a batch job" or "Log on as a service". You can find the details here:
The script to create a daily task which runs with a specific Windows user ID.
$task_folder = "\myTasks\"
$task_name = "myTask1"
$ps_script_file = "d:\temp5\test-script.ps1"
$exist = Get-ScheduledTask | where {$_.TaskPath -eq "\myTasks\" -and $_.TaskName -eq $task_name }
if (!$exist) {
$axn = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass -NoProfile -WindowStyle Hidden -File ""$ps_script_file"""
$tm = New-ScheduledTaskTrigger -Daily -At "23:00"
# you have to replace your Windows ID !!!
$sec = New-ScheduledTaskPrincipal -UserId "myPC\myUserID" -LogonType S4U -RunLevel Highest
Register-ScheduledTask -TaskName $task_name -TaskPath $task_folder -Action $axn -Trigger $tm -Principal $sec
Write-Host "created new task"
}
else {
Write-Host "The task already exists"
}
The schedule task location
Once a task has been created, it will be stored in the following folder.
C:\Windows\System32\Tasks\myTasks
Conclusion
For a server task, it is best to run in 'Local System' context which has the highest access permission in Windows server. For example, backing up the databases and then sync it to another server.
Related posts
- Create scheduled task in Windows Task Scheduler - part 1
- Create scheduled task in Windows Task Scheduler - part 2
- Create scheduled task in Windows Task Scheduler - part 3
Back to #POWERSHELL blog
Back to #blog listing
Author
Lau Hon Wan, software developer.