Skip to content

Instantly share code, notes, and snippets.

@xnohat
Created September 30, 2018 12:28
Show Gist options
  • Save xnohat/5a978cec6747be2aca24e07c85e3cdcf to your computer and use it in GitHub Desktop.
Save xnohat/5a978cec6747be2aca24e07c85e3cdcf to your computer and use it in GitHub Desktop.
Removing duplicate entries in NuGet packages.config
# Paste this entire script into NuGet Package Manager Console with an open solution in Visual Studio.
# This script will locate projects with duplicate dependencies in packages.config and remove them.
Function Get-Duplicate {
param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]$array, [switch]$count)
begin {
$hash = @{}
}
process {
$array | %{ $hash[$_] = $hash[$_] + 1 }
if($count) {
$hash.GetEnumerator() | ?{$_.value -gt 1} | %{
New-Object PSObject -Property @{
Value = $_.key
Count = $_.value
}
}
}
else {
$hash.GetEnumerator() | ?{$_.value -gt 1} | %{$_.key}
}
}
}
Get-Project -All | ForEach-Object {
$ProjectName = $_.ProjectName
$ProjectPackages = Get-Package -ProjectName $ProjectName
if ($ProjectPackages) {
$Dupes = Get-Duplicate ($ProjectPackages | ForEach-Object { $_.Id })
if (!$Dupes) {
Write-Host "No dupes found in $ProjectName"
}
else
{
ForEach ($Dupe in $Dupes) {
$First = $ProjectPackages | Where-Object { $_.Id -eq $Dupe } | Select-Object -First 1
# Note NuGet 2.0.30625.9003 happily ignores the version flag and uninstalls whatever the fuck it feels like.
Uninstall-Package -ProjectName $ProjectName -Id $($First.Id) -Version $($First.Version) -Force
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment