0
votes

I'm at my wits end trying to get a scheduled task to persist after a Windows Server 2019 reboot. I'm using powershell to create the scheduled task.

It triggers just fine and I can see it running before the reboot. Then the Server adds the ADDS component and Forest and reboots. After the reboot, no matter what I try, I can't get the scheduled task to start properly again.

Note that this exact code below works just fine on Windows 10 for adding a scheduled task to restart itself after a reboot. Any help appreciated. Are there some settings that need to be here for Windows Server that differ for Win10?

Here is the error description: After the reboot, in the task summary, it says "The last run of the task was terminated by the user" with last run time right before the reboot. The next run time keeps on incrementing every minute. In the History the error is, "Task Scheduler Failed to Start" with "Additional Data: Error Value: 2147943726."

# Create a scheduled task action
$sta = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -command "C:\Terraform\ImportUsers.ps1"'

# Create a schedule task trigger
$stt = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionDuration (New-TimeSpan -Days 1) -RepetitionInterval (New-TimeSpan -Minutes 1)

# Create a new scheduled task setting
$sts = New-ScheduledTaskSettingsSet -StartWhenAvailable -RestartInterval (New-TimeSpan -Minutes 1) -RestartCount 3 

# Set it to Stop the existing instance (for proper startup after reboot)
$sts.CimInstanceProperties.Item('MultipleInstances').Value = 3

# Register new scheduled task
Register-ScheduledTask ImportDomainUser01 -Action $sta -Settings $sts -Trigger $stt -User "LocalAdmin" -Password "LocalAdminPassword"
1

1 Answers

0
votes

I was able to get this working using powershell scheduled jobs instead of a traditional scheduled task. This solution below persists across a reboot on Windows Server 2019:

$jt = New-JobTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 1) -RepetitionDuration (New-Timespan -Hours 48)

Register-ScheduledJob -Name ImportUsers01 -ScriptBlock { C:\script.ps1 } -Trigger $jt