Skip to content

Instantly share code, notes, and snippets.

Forked from thoemmi/Clear-NuGetCache.ps1
Last active December 22, 2018 16:53
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Script to delete old NuGet packages from the default global packages folder which haven't been accessed for 150 days
[int]$CutoffDays = 150
$cutoffDate = (Get-Date).AddDays(-$CutoffDays)
# get path to cached NuGet packages
$nugetCachePath = .\Get-Nuget-Cache-Path.ps1
# get all package versions
$packages = gci -Path $nugetCachePath | gci
# get only those folders which weren't accessed since $cutoffDate, and also get their lengths
$oldPackages = $packages |
? { $_.LastAccessTimeUtc -le $cutoffDate } |
Sort-Object -Property LastAccessTime |
select Fullname,LastAccessTime,@{Name="Length";Expression={ (gci $_.Fullname -Recurse -Force | Measure-Object -Property Length -Sum).Sum }}
# delete those folder
$oldPackages | select -ExpandProperty Fullname | Remove-Item -Recurse
# output freed bytes
"{0:n2} Mb freed" -f (($oldPackages | Measure-Object -Property Length -Sum).Sum / 1Mb)
[string]$ConfigFile = Join-Path "$([System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::ApplicationData))" NuGet\NuGet.Config
if ([System.IO.File]::Exists($ConfigFile))
[xml]$ConfigXml = Get-Content $ConfigFile
$XPath = "/configuration/config/add[@key='globalPackagesFolder']/@value"
$globalPackagesFolder = Select-Xml -xml $ConfigXml -xpath $XPath
if (!$globalPackagesFolder)
Join-Path "$([System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::UserProfile))" ".nuget\packages"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment