Welcome to ciysys blog

Create scheduled task in Windows Task Scheduler - part 3

Published on: 27th Dec 2019

Updated on: 16th Jan 2022

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:

https://docs.microsoft.com/en-us/windows/win32/taskschd/principal-logontype

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:

https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/log-on-as-a-batch-job

https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/log-on-as-a-service

Once a task has been created, it will be stored in the following folder

C:\Windows\System32\Tasks\myTasks

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"
}

Jump to #POWERSHELL blog

Author

Lau Hon Wan, software developer.