On Windows 11, from an Administrator PowerShell 7.4 instance, I configured a Scheduled task as follows:
$action = New-ScheduledTaskAction -Execute 'PowerShell' -Argument 'C:\myscript.ps1'
$trigger = New-ScheduledTaskTrigger -Daily -At 11:00
$task = New-ScheduledTask -Action $action -Trigger $trigger
Register-ScheduledTask check_updates -InputObject $task
The script simply checks for updates and installs them:
"Scheduled task starts. Exit code was: " | Out-File -Append -NoNewline C:\log1.txt
$candidates = Get-WindowsUpdate
$LASTEXITCODE | Out-File -Append C:\log1.txt
if ($candidates) {
"There was at least one update" | Out-File -Append C:\log1.txt
foreach ($available_update in $candidates) {
if ($available_update.KB) {
Get-WindowsUpdate -KBArticleID $available_update.KB -Install -Confirm:$false
"There was a KB update" | Out-File -Append C:\log1.txt
} else {
Get-WindowsUpdate -Title $available_update.Title -Install -Confirm:$false
"There was a generic update" | Out-File -Append C:\log1.txt
}
}
}
Get-Date | Out-File -NoNewline -Append C:\log1.txt
" Scheduled task end" | Out-File -Append C:\log1.txt
This Scheduled task does not behave as exepected.
The fact that it has been created from an Administrator shell probably did not grant Administrator privileges to the script execution. But even the simple check Get-WindowsUpdate
requires Administrator privileges. $LASTEXITCODE
is always empty.
Also, sometimes the Scheduled task does not run at all, even if the system is active (not suspended). This seems to occur randomly. Anyway, the script never managed to download and apply an update when available.
May the Administrator privileges be a first reason for some of these failures? How to run a script as a Scheduled task with Administrator privileges?