Posted by Arjun Arjun on Monday 11th January 2021, 1 minute read

Automatically clean up docker on a windows machine?

To remove all stopped containers, all unused networks, all dangling images, and build caches we will execute the docker prune command as shown below. 

docker system prune -f
We are going to create a Windows Scheduled task with a PowerShell script to automatically delete all stopped containers, all dangling images, all unused networks, and build caches. 

The following script will setup Scheduled tasks to be run at 3 am UTC which will prune docker. Create a .ps1 file (ex: CreateDockerPruneWtask.ps1) with the below PowerShell script 

param(
    [string]$dockerPath = "C:\Program Files\Docker\docker.exe"
)

$action = New-ScheduledTaskAction -Execute $dockerPath -Argument "system prune -a -f"
$trigger = New-ScheduledTaskTrigger -Daily -At 3am
$Principle=New-ScheduledTaskPrincipal -GroupId "BUILTIN\Administrators" -RunLevel Highest
Register-ScheduledTask -Action $action -Principal $Principle -Trigger $trigger -TaskName "Docker-System-Prune" -Description "Docker System Prune"
Run the PowerShell script to create a Windows scheduled task, before running the script, please check docker.exe file path, if needed change the path according to the docker installation.

PS C:\Users\welcome> ./CreateDockerPruneWtask.ps1 --dockerPath = "C:\Program Files\Docker\docker.exe\docker.exe"
You can verify the task in Task Scheduler. to launch Task Scheduler from PowerShell use taskschd command. 
...
Arjun

I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.