Automatically update WSL distributions using the Windows Scheduler

  • Gérald Barré

Windows Subsystem for Linux (WSL) allows running one or multiple Linux distributions on Windows. Like any Operating System, you must install security updates on it. Instead of doing it manually, let's automate it using the Windows Scheduler!

Open PowerShell and run the following commands to create a scheduled task that updates the default WSL distribution once a week.

# https://docs.microsoft.com/en-us/powershell/module/scheduledtasks/new-scheduledtasktrigger
$Time = New-ScheduledTaskTrigger -At 12:00 -Weekly -WeeksInterval 1 -DaysOfWeek Monday

# https://docs.microsoft.com/en-us/powershell/module/scheduledtasks/new-scheduledtaskaction
# If you want to update a specific distro, you can add "--distribution <DistributionName>"
$Actions = @(
    New-ScheduledTaskAction -Execute "wsl" -Argument "--user root --exec apt-get update"
    New-ScheduledTaskAction -Execute "wsl" -Argument "--user root --exec apt-get upgrade --yes"
)

# https://docs.microsoft.com/en-us/powershell/module/scheduledtasks/new-scheduledtasksettingsset
$Settings = New-ScheduledTaskSettingsSet -WakeToRun:$false `
                                         -MultipleInstances IgnoreNew `
                                         -RunOnlyIfNetworkAvailable:$true `
                                         -StartWhenAvailable:$true

# https://docs.microsoft.com/en-us/powershell/module/scheduledtasks/register-scheduledtask
Register-ScheduledTask -TaskName "Update wsl" -Trigger $Time -Action $Actions -Settings $Settings -TaskPath Updates

If everything's good, you should see the new task in the Task Scheduler:

You can run the task manually once to validate it works well. It could take a few minutes if you have never updated the distro!

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee