Skip to content

Instantly share code, notes, and snippets.

@idiotandrobot
Forked from thoemmi/Clear-NuGetCache.ps1
Last active December 22, 2018 16:53
Show Gist options
  • Save idiotandrobot/3fe8322557923fe743aff77696fde46d to your computer and use it in GitHub Desktop.
Save idiotandrobot/3fe8322557923fe743aff77696fde46d to your computer and use it in GitHub Desktop.
Script to delete old NuGet packages from the default global packages folder which haven't been accessed for 150 days
[CmdletBinding(SupportsShouldProcess=$True)]
Param(
[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
# https://docs.microsoft.com/en-us/nuget/reference/nuget-config-file#config-section
$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"
}
else
{
$globalPackagesFolder.Node.Value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment