Skip to content

Instantly share code, notes, and snippets.

@eocron
Created May 19, 2023 08:25
Show Gist options
  • Save eocron/cf3f1cdb189125fad02079d5e2f46acd to your computer and use it in GitHub Desktop.
Save eocron/cf3f1cdb189125fad02079d5e2f46acd to your computer and use it in GitHub Desktop.
Remove csproj duplicate dependencies
param ($BasePath = './')
$CsProjects = Get-ChildItem -Path $BasePath -Filter '*.csproj' -File -recurse
foreach ($csProjFile in $CsProjects)
{
$path = $csProjFile.FullName
Write-Host $path
$xml = [XML](Get-Content $path)
$projNodes = $xml.SelectNodes("//Project/ItemGroup/PackageReference")
$distinctProjNodes = @{}
$toDeleteProjNodes = New-Object System.Collections.Generic.List[System.Object]
foreach($v in $projNodes)
{
$currentName = $v.Attributes['Include'].Value
$currentVersion = New-Object -TypeName System.Version -ArgumentList $v.Attributes['Version'].Value
if($distinctProjNodes.ContainsKey($currentName))
{
$existing = $distinctProjNodes[$currentName]
$existingVersion = New-Object -TypeName System.Version -ArgumentList $existing.Attributes['Version'].Value
if($existingVersion -ge $currentVersion)
{
$toDeleteProjNodes.Add($v)
}
else
{
$toDeleteProjNodes.Add($existing)
$distinctProjNodes[$currentName] = $v
}
}
else
{
$distinctProjNodes.Add($currentName, $v)
}
}
if($toDeleteProjNodes.Count -gt 0)
{
foreach($node in $toDeleteProjNodes)
{
$node.ParentNode.RemoveChild($node)
}
$xml.Save($path)
Write-Host "Updated file $($path)"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment