I am trying to use this method to get the .NET Framework directory (e.g. C:\Windows\Microsoft.NET\v4.0.30319)
Add-Type -AssemblyName Microsoft.Build.Utilities
$dotNetDir = [Microsoft.Build.Utilities.ToolLocationHelper]::GetPathToDotNetFramework([Microsoft.Build.Utilities.TargetDotNetFrameworkVersion]::VersionLatest)
However, it is returning nothing. No error, just blank.
I know there are other ways to get the .NET directory but I am wondering why this method is not working?
TL;DR The
Microsoft.Build.Utilitiesassembly doesn't support framework versions newer than 2.0. Use a newer assembly to get support for newer framework versions.On 64-bit Windows 10 Professional I get the following output...
I also notice that the
VersionLatestenumeration value is an alias forVersion20...That is,
VersionLatestevidently doesn't mean "find the latest installed framework version at runtime", it's just a flexible way to specify the latest available version known at compile-time (of thatMicrosoft.Build.Utilitiesassembly), of which there are not many...Regarding the results you see on different operating systems, Windows 7 has .NET 2.0 installed by default and, if I recall, Windows 10 has .NET 4.0 but not 2.0 installed by default, so if you didn't change anything that would explain why you get outdated results on Windows 7 and no results on Windows 10. I do have .NET 2.0 as an installed feature on Windows 10, which is why the method is able to find that framework directory.
To fix this, you need to use a newer
Microsoft.Build.Utilities*assembly, which uses a new name for each version. On my system I haveMicrosoft.Build.UtilitiesandMicrosoft.Build.Utilities.v3.5in the GAC, but the latter only supports up to .NET 3.5. Instead, I installedMicrosoft.Build.Utilities.Corefrom NuGet...After passing
Microsoft.Build.Utilities.Core.dlland its dependencies toAdd-Type, I get a much longer list ofMicrosoft.Build.Utilities.TargetDotNetFrameworkVersionvalues using the snippet above...Now your original code finally returns the directory for .NET 4.0...
I notice there is a new
Latestenumeration value as well which looks like it really does mean "the version of the latest installed framework", though it (currently) returns the same path as passingVersionLatest.