Files
system-automations/Register-ChocoUpgradeTask.ps1
T
2026-06-18 08:17:17 -05:00

54 lines
2.3 KiB
PowerShell

# Register-ChocoUpgradeTask.ps1
# Registers a scheduled task to run Upgrade-Choco.ps1 daily at 2:00 AM.
$TaskName = "Chocolatey Daily Upgrade"
$TaskDescription = "Runs choco upgrade all -y daily at 2:00 AM with Administrator privileges."
$ScriptPath = Join-Path $PSScriptRoot "Upgrade-Choco.ps1"
# Ensure the script exists
if (-not (Test-Path $ScriptPath)) {
Write-Error "Error: Upgrade-Choco.ps1 not found at $ScriptPath"
exit 1
}
Write-Output "Configuring scheduled task: $TaskName"
Write-Output "Target script: $ScriptPath"
# Define Action
$Action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$ScriptPath`""
# Define Trigger (Daily at 2:00 AM)
# Note: Using 2:00 AM for the trigger start boundary
$Trigger = New-ScheduledTaskTrigger -Daily -At "2:00 AM"
# Define Settings:
# - Allow start on batteries: Yes
# - Don't stop if going on batteries: Yes
# - Start when available: Yes (runs as soon as possible if a scheduled start is missed)
# - Execution time limit: 2 hours (in case it hangs)
$Settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Hours 2)
# Define Principal:
# Run as NT AUTHORITY\SYSTEM to ensure it runs elevated and doesn't require a logged-in user session.
$Principal = New-ScheduledTaskPrincipal -UserId "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest
# Register Scheduled Task (Overwrites if it already exists)
try {
# If task exists, unregister it first to avoid conflicts
if (Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue) {
Write-Output "Existing task found. Re-registering..."
Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
}
$Task = Register-ScheduledTask -TaskName $TaskName -Description $TaskDescription -Action $Action -Trigger $Trigger -Settings $Settings -Principal $Principal
Write-Output "Successfully registered scheduled task '$TaskName'."
Write-Output "Task details:"
Write-Output " State: $($Task.State)"
Write-Output " Trigger: Daily at 2:00 AM"
Write-Output " Principal: $($Task.Principal.UserId) ($($Task.Principal.RunLevel))"
}
catch {
Write-Error "Failed to register scheduled task: $_"
exit 1
}