Why does Powershell have access to methods introduced in a newer .net version?

Viewed 255

it seems Powershell v5.1 uses .Net Framework v4.0

[Environment]::Version
# Major  Minor  Build  Revision
# -----  -----  -----  --------
# 4      0      30319  42000

and DateTimeOffset.FromUnixTimeSeconds method requires .Net Framework v4.6+ , so basically Powershell v5.1 should not have access to it. but ...

[DateTimeOffset]|Get-Member -Static -Name FromUnixTimeSeconds
# TypeName: System.DateTimeOffset
# Name                MemberType Definition
# ----                ---------- ----------
# FromUnixTimeSeconds Method     static System.DateTimeOffset FromUnixTimeSeconds(long seconds)

Why am I able to call it? Does it have something to do with C# AssemblyVersion & AssemblyFileVersion?

1 Answers

[Environment]::Version reports the CLR (the runtime) version, which is not the same as the .NET Framework version, which is the independently versioned class library[1] that builds on a given CLR version.

To get the framework version, use the following, which returns a string such as
".NET Framework 4.8.4341.0":

[System.Runtime.InteropServices.RuntimeInformation]::FrameworkDescription

Note:

  • This property is available in .NET Framework 4.7.1 and above.

    • Caveat: As Bacon Bits reports, a 2.0 beta version of the PSReadLineModule module can shadow the property due to inexplicably being bundled with an older version of the [System.Runtime.InteropServices.RuntimeInformation] class. If so, upgrade to the latest stable version, which is 2.1 as of this writing; see the comments for details.
  • If it isn't available, you can try the following, which yields a string such as "4.8.04084":[2]

    Get-ItemPropertyValue 'registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full' Version
    
  • If that doesn't work either, the implication is that your .NET Framework version is lower than 4.5


[1] In the cross-platform .NET Core / .NET 5+ edition, there is only a unified runtime that also includes the class library, which [Environment]::Version correctly reflects in .NET Core 3.0 and later.

[2] Curiously, this version differs in the revision number from the one reported by [System.Runtime.InteropServices.RuntimeInformation]::FrameworkDescription (if available). There's yet another variant with a differing revision, as part of the InstallPath value from the same registry key; e.g. C:\Windows\Microsoft.NET\Framework64\v4.0.30319\

Related