What am I doing here? I keep getting Register-ScheduledTask: The parameter is incorrect.
I tried different combinations but same problem! I'm running PowerShell 4 on WinServer2012 and as System. This runs fine on PS7 and PS5.
$taskname = "anyname"
$action = New-ScheduledTaskAction -Execute $sysprepCommand -Argument $sysprepParameters
$principal = New-ScheduledTaskPrincipal -RunLevel Highest -UserId SYSTEM
New-ScheduledTask -Action $action -Principal $principal | Register-ScheduledTask -TaskName $taskname -Force | Start-ScheduledTask | Unregister-ScheduledTask -Confirm:$false
The parameter -Principal $principal
is correct and fine. However, for 2012er Systems you need to add -LogonType ServiceAccount
in case you want to use a ServiceAccount instead of a UserAccount.
Example from my environment (tested on WinSvr 2012 - 2022):
$ComputerName = $env:Computername
$Action1 = New-ScheduledTaskAction -Execute "msiexec.exe" -Argument "/I AzureConnectedMachineAgent.msi /l*v $($ComputerName)_azcmagent_update.log /qn"
$Action2 = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "Disable-ScheduledTask -TaskName 'azcmagent'"
$actions = @($Action1, $Action2)
$Trigger = New-ScheduledTaskTrigger -Weekly -WeeksInterval 4 -DaysOfWeek "Saturday" -At 10AM
$taskPrincipal = New-ScheduledTaskPrincipal -UserId "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest
$ScheduledTask = New-ScheduledTask -Action $actions -Trigger $trigger -Description $TaskDescription -Principal $taskPrincipal
Register-ScheduledTask -TaskName $TaskName -InputObject $ScheduledTask