-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemove-DockerArtifact.ps1
More file actions
667 lines (572 loc) · 24.8 KB
/
Copy pathRemove-DockerArtifact.ps1
File metadata and controls
667 lines (572 loc) · 24.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
function Remove-DockerArtifact
{
<#
.SYNOPSIS
Cleans up unused Docker artifacts with safety controls.
.DESCRIPTION
Removes unused Docker images, networks, build cache, and (optionally) stopped containers, volumes,
Buildx builder instances, and Docker Desktop build history.
Supports -WhatIf/-Confirm and lets you choose between pruning all unused images or only dangling ones.
For -WhatIf, EstimatedReclaimable is calculated by scanning unused images so you know what would be freed.
By default:
- Unused images (not just dangling) are pruned
- Unused networks and build cache are pruned
- Stopped containers are NOT removed unless -IncludeStoppedContainers is specified
- Volumes are NOT removed unless -IncludeVolumes is specified
- Buildx builder instances are NOT removed unless -IncludeBuildxBuilders is specified
- Docker Desktop build history is NOT removed unless -IncludeBuildHistory is specified
Cross-platform compatible with PowerShell 5.1+ on Windows, macOS, and Linux. Requires Docker CLI
to be installed and available in PATH.
.PARAMETER All
Convenience switch that includes all cleanup categories: stopped containers, unused volumes,
Buildx builder instances, and Docker Desktop build history.
.PARAMETER IncludeStoppedContainers
Also remove stopped containers. When specified, cleanup uses 'docker system prune' to mirror Docker's
built-in behavior (including images, networks, build cache, and optionally volumes).
.PARAMETER DanglingImagesOnly
Restrict image pruning to dangling images only (same as omitting '--all'). By default, all unused
images are pruned to maximize reclaimed space.
.PARAMETER IncludeVolumes
Also prune unused volumes. Volumes can hold data you care about; use -WhatIf or -Confirm first if unsure.
.PARAMETER IncludeBuildxBuilders
Also remove Buildx builders that use the 'docker-container' driver. This removes their BuildKit
containers so pinned images like 'moby/buildkit:buildx-stable-1' can be pruned in the same run.
.PARAMETER IncludeBuildHistory
Also remove Docker Desktop build records from the current buildx builder and prune BuildKit cache.
This runs:
- 'docker buildx history rm --all' (removes records shown in Docker Desktop Build History)
- 'docker buildx prune --all --force' (removes reusable build cache entries)
.EXAMPLE
PS > Remove-DockerArtifact
PS > # Unused images (all), networks, and build cache pruned; containers and volumes untouched
Runs a safe cleanup that leaves stopped containers and volumes alone while reclaiming image, network,
and build cache space.
.EXAMPLE
PS > Remove-DockerArtifact -IncludeStoppedContainers -IncludeVolumes
Performs a full 'docker system prune --all --volumes', removing stopped containers, unused images,
networks, build cache, and unused volumes.
.EXAMPLE
PS > Remove-DockerArtifact -DanglingImagesOnly -IncludeStoppedContainers
Mirrors 'docker system prune' default behavior: removes stopped containers, dangling images, unused
networks, and build cache while keeping non-dangling unused images.
.EXAMPLE
PS > Remove-DockerArtifact -IncludeStoppedContainers -WhatIf
Shows what a full system prune would remove without actually deleting anything and displays an
estimated reclaimable size for unused images.
.EXAMPLE
PS > Remove-DockerArtifact -IncludeVolumes -Confirm
Prompts for confirmation before removing unused volumes along with images, networks, and build cache.
.EXAMPLE
PS > Remove-DockerArtifact -IncludeBuildHistory
Includes Docker Desktop build history cleanup by removing build records and pruning build cache.
.EXAMPLE
PS > Remove-DockerArtifact -IncludeBuildxBuilders
Removes Buildx builders that use the docker-container driver so their BuildKit containers no longer
hold BuildKit images in-use.
.EXAMPLE
PS > Remove-DockerArtifact -All
Includes stopped containers, unused volumes, Buildx builder instances, and Docker Desktop build
history in a single cleanup run.
.OUTPUTS
[PSCustomObject]
Returns an object with summary information:
- ContainersPruned : $true if stopped containers were included
- VolumesPruned : $true if volumes were included
- BuildxBuildersPruned : $true if Buildx builder removal was included
- BuildHistoryPruned : $true if Docker Desktop build history cleanup was included
- ImageMode : 'AllUnused' or 'DanglingOnly'
- EstimatedReclaimable : Estimated unused image size in -WhatIf runs; otherwise reports not calculated
- TotalSpaceFreed : Total space freed based on prune output (formatted string)
- Errors : Number of errors encountered
.NOTES
- Requires Docker CLI
- Respects -WhatIf and -Confirm for safety
- Buildx builder cleanup only targets builders using the 'docker-container' driver
- When -IncludeStoppedContainers is not used, pruning is composed of targeted image/network/builder
commands to avoid touching containers
Author: Jon LaBelle
License: MIT
Source: https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/Developer/Remove-DockerArtifact.ps1
.LINK
https://docs.docker.com/reference/cli/docker/system/prune/
.LINK
https://docs.docker.com/reference/cli/docker/volume/prune/
.LINK
https://docs.docker.com/reference/cli/docker/buildx/prune/
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
[CmdletBinding(SupportsShouldProcess)]
[OutputType([PSCustomObject])]
param(
[Parameter()]
[Switch]$All,
[Parameter()]
[Switch]$IncludeStoppedContainers,
[Parameter()]
[Switch]$DanglingImagesOnly,
[Parameter()]
[Switch]$IncludeVolumes,
[Parameter()]
[Switch]$IncludeBuildxBuilders,
[Parameter()]
[Switch]$IncludeBuildHistory
)
begin
{
Write-Verbose 'Starting Docker artifacts cleanup'
$stats = @{
ContainersPruned = $false
VolumesPruned = $false
BuildxBuildersPruned = $false
BuildHistoryPruned = $false
ImageMode = if ($DanglingImagesOnly) { 'DanglingOnly' } else { 'AllUnused' }
SpaceFreedBytes = [int64]0
EstimatedReclaimableBytes = [int64]0
EstimatedReclaimableEstimateSucceeded = $false
Errors = 0
}
$dockerCommand = Get-Command -Name 'docker' -ErrorAction SilentlyContinue
if (-not $dockerCommand)
{
throw 'Docker is not installed or not available in PATH. Please install Docker and try again.'
}
Write-Verbose "Docker found at: $($dockerCommand.Source)"
if ($All -and $DanglingImagesOnly)
{
throw 'The -All and -DanglingImagesOnly parameters cannot be used together.'
}
function Convert-SizeStringToBytes
{
param([String]$SizeString)
if ([string]::IsNullOrWhiteSpace($SizeString))
{
return [int64]0
}
$clean = $SizeString.Trim()
$clean = $clean -replace '\(.*\)', '' -replace '\s+', ''
if ($clean -match '^(?<Value>[0-9]+(?:\.[0-9]+)?)(?<Unit>[kmgtpe]?i?b)?$')
{
$value = [double]$matches['Value']
$unit = $matches['Unit'].ToLower()
switch ($unit)
{
'kb' { return [int64]($value * 1KB) }
'kib' { return [int64]($value * 1KB) }
'mb' { return [int64]($value * 1MB) }
'mib' { return [int64]($value * 1MB) }
'gb' { return [int64]($value * 1GB) }
'gib' { return [int64]($value * 1GB) }
'tb' { return [int64]($value * 1TB) }
'tib' { return [int64]($value * 1TB) }
default { return [int64]$value }
}
}
return [int64]0
}
function Format-ByteSize
{
param([int64]$Bytes)
switch ($Bytes)
{
{ $_ -ge 1TB } { '{0:N2} TB' -f ($_ / 1TB); break }
{ $_ -ge 1GB } { '{0:N2} GB' -f ($_ / 1GB); break }
{ $_ -ge 1MB } { '{0:N2} MB' -f ($_ / 1MB); break }
{ $_ -ge 1KB } { '{0:N2} KB' -f ($_ / 1KB); break }
default { '{0} bytes' -f $_ }
}
}
function Convert-ImageId
{
param([string]$Id)
if ([string]::IsNullOrWhiteSpace($Id))
{
return $null
}
$trimmed = $Id.Trim()
if ($trimmed.Length -gt 12)
{
return $trimmed.Substring(0, 12)
}
return $trimmed
}
function Get-UnusedImageEstimate
{
param([Switch]$DanglingOnly)
try
{
$inUseIds = @()
try
{
$inUseIds = & $dockerCommand.Name ps -a --format '{{.ImageID}}' 2>&1 |
ForEach-Object { $_.ToString().Trim() } |
Where-Object { $_ -ne '' }
}
catch
{
Write-Verbose "Failed to collect in-use container images: $($_.Exception.Message)"
}
$inUseSet = New-Object System.Collections.Generic.HashSet[string]
foreach ($id in $inUseIds)
{
$normalized = Convert-ImageId $id
if ($normalized) { $null = $inUseSet.Add($normalized) }
}
$imagesOutput = & $dockerCommand.Name image ls --format '{{json .}}' 2>&1
$totalBytes = [int64]0
$count = 0
foreach ($line in $imagesOutput)
{
$lineText = $line.ToString()
if ([string]::IsNullOrWhiteSpace($lineText)) { continue }
try
{
$img = $lineText | ConvertFrom-Json
$imageId = Convert-ImageId $img.ID
$isDangling = ($img.Repository -eq '<none>') -or ($img.Tag -eq '<none>')
if ($DanglingOnly -and -not $isDangling)
{
continue
}
$isInUse = $false
if ($imageId)
{
foreach ($inUse in $inUseSet)
{
if ($inUse -and ($imageId.StartsWith($inUse, [System.StringComparison]::OrdinalIgnoreCase) -or
$inUse.StartsWith($imageId, [System.StringComparison]::OrdinalIgnoreCase)))
{
$isInUse = $true
break
}
}
}
if (-not $isInUse)
{
$count++
$totalBytes += Convert-SizeStringToBytes $img.Size
}
}
catch
{
Write-Verbose "Failed to parse docker image entry for estimation: $($_.Exception.Message)"
}
}
return [PSCustomObject]@{
Count = $count
Bytes = $totalBytes
}
}
catch
{
Write-Verbose "Failed to estimate unused images: $($_.Exception.Message)"
return [PSCustomObject]@{
Count = 0
Bytes = 0
}
}
}
function Invoke-DockerPrune
{
param(
[String[]]$Arguments,
[String]$Description
)
$reclaimedBytes = [int64]0
if ($PSCmdlet.ShouldProcess('Docker daemon', $Description))
{
try
{
$output = & $dockerCommand.Name @Arguments 2>&1
$exitCode = $LASTEXITCODE
if ($exitCode -ne 0)
{
$stats.Errors++
$errorSummary = $null
if ($output)
{
$errorSummary = $output |
ForEach-Object { $_.ToString().Trim() } |
Where-Object { $_ -ne '' } |
Select-Object -First 1
}
if ($errorSummary)
{
Write-Warning "Failed to run 'docker $($Arguments -join ' ')' (exit code $exitCode): $errorSummary"
}
else
{
Write-Warning "Failed to run 'docker $($Arguments -join ' ')' (exit code $exitCode)."
}
return [int64]0
}
foreach ($line in $output)
{
if ($line -match 'Total reclaimed space:\s*(.+)$')
{
$reclaimedBytes = Convert-SizeStringToBytes $matches[1]
break
}
elseif ($line -match '^Total:\s*(.+)$')
{
# buildx prune reports reclaimed size as "Total: <size>"
$reclaimedBytes = Convert-SizeStringToBytes $matches[1]
break
}
}
}
catch
{
$stats.Errors++
Write-Warning "Failed to run 'docker $($Arguments -join ' ')': $($_.Exception.Message)"
}
}
else
{
Write-Verbose "WhatIf: Would run 'docker $($Arguments -join ' ')'"
}
return $reclaimedBytes
}
function Remove-BuildxContainerBuilders
{
[CmdletBinding(SupportsShouldProcess)]
param()
$builderNames = @()
$listArgs = @('buildx', 'ls', '--format', '{{json .}}')
try
{
$listOutput = & $dockerCommand.Name @listArgs 2>&1
$listExitCode = $LASTEXITCODE
if ($listExitCode -ne 0)
{
$stats.Errors++
$errorSummary = $null
if ($listOutput)
{
$errorSummary = $listOutput |
ForEach-Object { $_.ToString().Trim() } |
Where-Object { $_ -ne '' } |
Select-Object -First 1
}
if ($errorSummary)
{
Write-Warning "Failed to run 'docker $($listArgs -join ' ')' (exit code $listExitCode): $errorSummary"
}
else
{
Write-Warning "Failed to run 'docker $($listArgs -join ' ')' (exit code $listExitCode)."
}
return
}
foreach ($line in $listOutput)
{
$lineText = $line.ToString()
if ([string]::IsNullOrWhiteSpace($lineText)) { continue }
try
{
$builder = $lineText | ConvertFrom-Json
if ($builder -and
$builder.Driver -eq 'docker-container' -and
-not [string]::IsNullOrWhiteSpace($builder.Name))
{
$builderNames += $builder.Name.Trim()
}
}
catch
{
Write-Verbose "Failed to parse buildx builder entry: $($_.Exception.Message)"
}
}
}
catch
{
$stats.Errors++
Write-Warning "Failed to run 'docker $($listArgs -join ' ')': $($_.Exception.Message)"
return
}
$builderNames = $builderNames | Sort-Object -Unique
if (-not $builderNames -or $builderNames.Count -eq 0)
{
Write-Verbose 'No docker-container Buildx builders found to remove.'
return
}
foreach ($builderName in $builderNames)
{
$removeArgs = @('buildx', 'rm', '--force', $builderName)
$description = "docker $($removeArgs -join ' ')"
if ($PSCmdlet.ShouldProcess("Docker Buildx builder '$builderName'", $description))
{
try
{
$removeOutput = & $dockerCommand.Name @removeArgs 2>&1
$removeExitCode = $LASTEXITCODE
if ($removeExitCode -ne 0)
{
$stats.Errors++
$errorSummary = $null
if ($removeOutput)
{
$errorSummary = $removeOutput |
ForEach-Object { $_.ToString().Trim() } |
Where-Object { $_ -ne '' } |
Select-Object -First 1
}
if ($errorSummary)
{
Write-Warning "Failed to run 'docker $($removeArgs -join ' ')' (exit code $removeExitCode): $errorSummary"
}
else
{
Write-Warning "Failed to run 'docker $($removeArgs -join ' ')' (exit code $removeExitCode)."
}
}
}
catch
{
$stats.Errors++
Write-Warning "Failed to run 'docker $($removeArgs -join ' ')': $($_.Exception.Message)"
}
}
else
{
Write-Verbose "WhatIf: Would run 'docker $($removeArgs -join ' ')'"
}
}
}
}
process
{
$includeStoppedContainersEffective = $IncludeStoppedContainers -or $All
$includeVolumesEffective = $IncludeVolumes -or $All
$includeBuildxBuildersEffective = $IncludeBuildxBuilders -or $All
$includeBuildHistoryEffective = $IncludeBuildHistory -or $All
# Estimate unused image space only for WhatIf previews
$shouldEstimate = $WhatIfPreference -eq $true
if ($shouldEstimate)
{
$estimate = Get-UnusedImageEstimate -DanglingOnly:$DanglingImagesOnly
if ($estimate)
{
$stats.EstimatedReclaimableEstimateSucceeded = $true
$stats.EstimatedReclaimableBytes = $estimate.Bytes
}
}
$reclaimedTotal = [int64]0
if ($includeBuildxBuildersEffective)
{
$stats.BuildxBuildersPruned = $true
Remove-BuildxContainerBuilders
}
if ($includeStoppedContainersEffective)
{
$stats.ContainersPruned = $true
$systemPruneArgs = @('system', 'prune', '--force')
if (-not $DanglingImagesOnly)
{
$systemPruneArgs += '--all'
}
if ($includeVolumesEffective)
{
$stats.VolumesPruned = $true
$systemPruneArgs += '--volumes'
}
$reclaimedTotal += Invoke-DockerPrune -Arguments $systemPruneArgs -Description "docker $($systemPruneArgs -join ' ')"
}
else
{
$imageArgs = @('image', 'prune', '--force')
if (-not $DanglingImagesOnly)
{
$imageArgs += '--all'
}
$reclaimedTotal += Invoke-DockerPrune -Arguments $imageArgs -Description "docker $($imageArgs -join ' ')"
$networkArgs = @('network', 'prune', '--force')
$reclaimedTotal += Invoke-DockerPrune -Arguments $networkArgs -Description "docker $($networkArgs -join ' ')"
$builderArgs = @('builder', 'prune', '--force')
if (-not $DanglingImagesOnly)
{
$builderArgs += '--all'
}
$reclaimedTotal += Invoke-DockerPrune -Arguments $builderArgs -Description "docker $($builderArgs -join ' ')"
if ($includeVolumesEffective)
{
$stats.VolumesPruned = $true
$volumeArgs = @('volume', 'prune', '--force')
$reclaimedTotal += Invoke-DockerPrune -Arguments $volumeArgs -Description "docker $($volumeArgs -join ' ')"
}
}
if ($includeBuildHistoryEffective)
{
$stats.BuildHistoryPruned = $true
$buildHistoryRecordsArgs = @('buildx', 'history', 'rm', '--all')
$reclaimedTotal += Invoke-DockerPrune -Arguments $buildHistoryRecordsArgs -Description "docker $($buildHistoryRecordsArgs -join ' ')"
$buildHistoryArgs = @('buildx', 'prune', '--all', '--force')
$reclaimedTotal += Invoke-DockerPrune -Arguments $buildHistoryArgs -Description "docker $($buildHistoryArgs -join ' ')"
}
}
end
{
$stats.SpaceFreedBytes = $reclaimedTotal
$isWhatIf = $WhatIfPreference -eq $true
$estimateSucceeded = $stats.EstimatedReclaimableEstimateSucceeded -eq $true
$estimatedDisplay = if ($isWhatIf)
{
if (-not $estimateSucceeded)
{
'Unable to estimate (unknown)'
}
elseif ($stats.EstimatedReclaimableBytes -gt 0)
{
Format-ByteSize $stats.EstimatedReclaimableBytes
}
else
{
'0 bytes (nothing unused detected)'
}
}
else
{
'Not calculated (use -WhatIf to preview)'
}
$result = [PSCustomObject]@{
ContainersPruned = $stats.ContainersPruned
VolumesPruned = $stats.VolumesPruned
BuildxBuildersPruned = $stats.BuildxBuildersPruned
BuildHistoryPruned = $stats.BuildHistoryPruned
ImageMode = $stats.ImageMode
EstimatedReclaimable = $estimatedDisplay
TotalSpaceFreed = Format-ByteSize $stats.SpaceFreedBytes
Errors = $stats.Errors
}
Write-Host "`nDocker Cleanup Summary:" -ForegroundColor Cyan
Write-Host " Containers pruned : $($result.ContainersPruned)" -ForegroundColor White
Write-Host " Volumes pruned : $($result.VolumesPruned)" -ForegroundColor White
Write-Host " Buildx builders : $($result.BuildxBuildersPruned)" -ForegroundColor White
Write-Host " Build history : $($result.BuildHistoryPruned)" -ForegroundColor White
Write-Host " Image mode : $($result.ImageMode)" -ForegroundColor White
if ($isWhatIf)
{
Write-Host " Estimated reclaimable: $($result.EstimatedReclaimable)" -ForegroundColor Yellow
Write-Host ' No changes made (WhatIf).' -ForegroundColor Yellow
}
Write-Host " Space freed : $($result.TotalSpaceFreed)" -ForegroundColor Green
if ($result.Errors -gt 0)
{
Write-Host " Errors : $($result.Errors)" -ForegroundColor Red
}
Write-Verbose 'Docker cleanup completed'
return $result
}
}
# Create 'docker-prune' alias only if it doesn't already exist
if (-not (Get-Command -Name 'docker-prune' -ErrorAction SilentlyContinue))
{
try
{
Write-Verbose "Creating 'docker-prune' alias for Remove-DockerArtifact"
Set-Alias -Name 'docker-prune' -Value 'Remove-DockerArtifact' -Force -ErrorAction Stop
}
catch
{
Write-Warning "Remove-DockerArtifact: Could not create 'docker-prune' alias: $($_.Exception.Message)"
}
}