Create a Scheduled Task to keep all Chocolatey Packages up-to-date

Rebuilding your PC is always a drag, even with useful utilities like Ninite.

I recently created a PowerShell DSC script that I can use whenever I need to rebuild my PC. As part of that, I used the cChoco provider to automatically install applications using Chocolatey. I’ll be writing a blog post with more details shortly.

That’s a great way to get the applications installed, but not for keeping them up-to-date. Chocolatey allows you to run ‘choco upgrade all’ manually to do this:

Command prompt window showing the results of a 'choco upgrade all -y' command

Rather than manually create the scheduled task to automate this, I created this short PowerShell script:

# See if choco.exe is available. If not, stop execution
$chocoCmd = Get-Command Name 'choco' ErrorAction SilentlyContinue WarningAction SilentlyContinue | Select-Object ExpandProperty Source
if ($chocoCmd -eq $null) { break }
# Settings for the scheduled task
$taskAction = New-ScheduledTaskAction –Execute $chocoCmd Argument 'upgrade all -y'
$taskTrigger = New-ScheduledTaskTrigger AtStartup
$taskUserPrincipal = New-ScheduledTaskPrincipal UserId 'SYSTEM'
$taskSettings = New-ScheduledTaskSettingsSet Compatibility Win8
# Set up the task, and register it
$task = New-ScheduledTask Action $taskAction Principal $taskUserPrincipal Trigger $taskTrigger Settings $taskSettings
Register-ScheduledTask TaskName 'Run a Choco Upgrade All at Startup' InputObject $task Force

The script will:

  1. Locate the choco.exe binary (It’ll quit if it can’t find it in the path)
  2. Set up a scheduled task that runs said binary at system startup

Note that this script will only work on Windows 8 and newer machines, because it relies on the *-ScheduledTask cmdlets.