# Register-WingetMsStoreTask.ps1 # Registers a scheduled task to run Upgrade-WingetMsStore.ps1 daily at 2:00 AM. $TaskName = "WinGet MS Store Upgrade" $TaskDescription = "Runs winget upgrade for MS Store packages daily at 2:00 AM." $ScriptPath = Join-Path $PSScriptRoot "Upgrade-WingetMsStore.ps1" # Ensure the script exists if (-not (Test-Path $ScriptPath)) { Write-Error "Error: Upgrade-WingetMsStore.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) $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 $Settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Hours 2) # Define Principal: # Run as the active user (jasonross) with Highest privileges since winget is user-context tied. # LogonType is set to Interactive to ensure the user profile and environment variables are loaded. $Principal = New-ScheduledTaskPrincipal -UserId "jasonross" -LogonType Interactive -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 }