Skip to content

Instantly share code, notes, and snippets.

@stesee
Created September 14, 2024 10:24
# Define the task name
$taskName = "ChocoUpgrade"
# Remove existing task if it exists
if (Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue) {
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false
Write-Host "Existing scheduled task '$taskName' removed."
}
# Define the log file path on the Desktop
$logFilePath = [System.IO.Path]::Combine([System.Environment]::GetFolderPath('Desktop'), 'choco_upgrade_log.txt')
# Define the action to run choco upgrade and write output to log file
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-Command `"choco upgrade all -y | Out-File -Append -FilePath '$logFilePath'`""
# Define the trigger to run weekly at 2 AM on Sundays
$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -At 2am
# Get the current user
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
# Define the principal to run the task with the current user
$principal = New-ScheduledTaskPrincipal -UserId $currentUser -LogonType Interactive -RunLevel Highest
# Create the scheduled task
Register-ScheduledTask -Action $action -Trigger $trigger -Principal $principal -TaskName $taskName -Description "Weekly upgrade of all Chocolatey packages"
Write-Host "Scheduled task '$taskName' created successfully."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment