Creating a One-Time-Task that runs with system rights after restart

By | February 20, 2020

There might be cases where you run a ConfigMgr task sequence and want to launch a task in the system context after the TS is finished. You can of course do this by using the task sequence variable SMSTSPOSTACTION but if you want to trigger an action after a restart a scheduled task might be the right option. The task sequence below demonstrates this. It can of course also be used to just start a task with a delay (the code is uncommented).

Download TS

As you see in the screenshot, there are basically three steps required:

Create Scheduled Task uses PowerShell to create an entry in the Task Scheduler that launches a cmd file.

<#This code is provided AS-IS and without any warranty#>

$triggers = @()

$taskname = “OneTimeTask”

$taskdescription = “Run the script at startup. The script should delete this scheduled task”

$action = New-ScheduledTaskAction “c:\windows\temp\runps.cmd”

$Trigger1 = New-ScheduledTaskTrigger -AtStartup

$settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 20) -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 60)

#$tNowPlus5min = Get-Date

#$tNowPlus5min = $tNowPlus5min.AddMinutes(5)

$triggers += $Trigger1

Register-ScheduledTask -Action $action -Trigger $triggers -TaskName $taskname -Description $taskdescription -Settings $settings -User “System” -RunLevel Highest

The scripts to be launched get copied in the Copy Scripts step. Since they are only temporarily required, we put them in %Windir%\temp. We launch a cmd which calls a PowerShell script, therefore we have two files. You may of course call a PowerShell script directly. Copy OneTimeTask Scripts is a simple package that contains a cmd with copy commands:

copy %~dp0runps.cmd %WINDIR%\temp

copy %~dp0SetInitialdeviceConfiguration.ps1 %WINDIR%\temp

It also contains the scripts to be launched by the scheduled task. For this example, it’s a cmd that calls a ps1 and then deletes the scheduled task by running SCHTASKS /DELETE /TN “OneTimeTask” /F and finally cleans up %Windir%\temp. If you ran the TS successfully and restarted the machine you will only find two log files with a time entry in that folder.

Requirements: The step Create Scheduled Task uses the feature to enter PowerShell code in the Task Sequence step Run PowerShell Step that was introduced with 1902. For older versions you must provide a package with the script.

2 thoughts on “Creating a One-Time-Task that runs with system rights after restart

Leave a Reply

Your email address will not be published. Required fields are marked *