Skip to content

Instantly share code, notes, and snippets.

@nehemiahj
Last active November 5, 2021 09:33
Show Gist options
  • Save nehemiahj/f5906fac905b04cd22fdbb9e96ec13f3 to your computer and use it in GitHub Desktop.
Save nehemiahj/f5906fac905b04cd22fdbb9e96ec13f3 to your computer and use it in GitHub Desktop.
Update .NET Framework Target Version in Legacy and SDK Project Formats
# This script updates .NET Target Framework version in both SDK and Legacy Project format types.
using namespace System.Collections.Generic
# Provide the src folder where the csproj files are located.
# This script can check the child folders as well.
$dir = "C:\Helix\src"
# Provide the target framework version
$legacyTargetFrameworkVersion = "v4.7.2";
$sdkTargetFrameworkVersion = "net472";
$projFiles = Get-ChildItem $dir -Recurse -Filter *.csproj
$projsWithVersion = [List[object]]::new()
foreach($file in $projFiles)
{
$content = [xml](Get-Content $file.FullName)
$legacyVersionNodes = $content.GetElementsByTagName("TargetFrameworkVersion");
$sdkVersionNodes = $content.GetElementsByTagName("TargetFramework");
$projectType = 0
if ($legacyVersionNodes.Count -eq 1)
{
# Legacy
$projectType = 1
}
elseif ($sdkVersionNodes.Count -eq 1)
{
# SDK
$projectType = 2
}
else
{
Write-Host "The project has no framework version node: $file.FullName"
}
switch($projectType)
{
0 {
Write-Host "The project has no framework version: $file.FullName"
break;
}
1 {
# Legacy
$version = $legacyVersionNodes[0].InnerText;
$projsWithVersion.Add([PsCustomObject]@{
File = $file;
XmlContent = $content;
VersionNode = $legacyVersionNodes[0];
VersionRaw = $version;
ProjectType = "Legacy";
})
break;
}
2 {
# SDK
$version = $sdkVersionNodes[0].InnerText;
$projsWithVersion.Add([PsCustomObject]@{
File = $file;
XmlContent = $content;
VersionNode = $sdkVersionNodes[0];
VersionRaw = $version;
ProjectType = "SDK";
})
break;
}
default {
Write-Host "Could not change the framework version: $file.FullName"
break;
}
}
}
# Loop through each list item and update the project.
foreach($proj in $projsWithVersion)
{
# If the project framework version is already beyond the target version, it will be skipped.
if ($proj.ProjectType -eq "Legacy") {
$proj.VersionNode.set_InnerXML("$legacyTargetFrameworkVersion")
$proj.XmlContent.Save($proj.File.FullName);
}
elseif ($proj.ProjectType -eq "SDK") {
$proj.VersionNode.set_InnerXML("$sdkTargetFrameworkVersion")
$proj.XmlContent.Save($proj.File.FullName);
}
}
# Reference: https://www.thinktecture.com/en/net/bulk-update-of-net-framework-version-powershell/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment