views:

124

answers:

6

I'd like to use .NET in some PowerShell scripts I'm about to write -- how do I know/declare which version of .NET I'm dealing with when these scripts run?

EDIT: And is it possible to choose against which version of .NET my script will run?

+1  A: 

Check this article out: http://blogs.technet.com/b/heyscriptingguy/archive/2009/01/05/how-do-i-check-which-version-of-windows-powershell-i-m-using.aspx

It shows where in the registry you can check to determine this.

spinon
+3  A: 

The .NET version can be inferred from the version of mscorlib. So you can do the following in PowerShell to output the current version of .NET:

$a = [System.Reflection.Assembly]::Load("mscorlib")
$a.GetName().Version
driis
You don't have to load mscorlib since it's already loaded into the application domain by default: `([AppDomain]::CurrentDomain.GetAssemblies() | ? { $_.GetName().Name -eq "mscorlib" }).GetName().Version`
George Howarth
easier to just use: [environment]::Version
x0n
A: 

I've found out that you can look for that information in the directory C:\Windows\Microsoft.NET\Framework:

cd C:\Windows\Microsoft.NET\Framework
dir

The directories inside that one will tell you the versions of the framework installed.

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        14/07/2009     10:48            3082
d----        14/07/2009      4:37            v1.0.3705
d----        14/07/2009      4:37            v1.1.4322
d----        25/06/2010     17:26            v2.0.50727
d----        14/07/2009     10:48            v3.0
d----        14/07/2009     10:48            v3.5
Baltasarq
+2  A: 

To get the .NET version:

[System.Reflection.Assembly]::GetExecutingAssembly().ImageRuntimeVersion

...which is, by default, the version of the CLR the assembly (System.Management.Automation.dll) compiled under.

And no, you cannot choose which .NET version you can run the script under.

George Howarth
powershell.exe is hard-coded to load v2.0 of the CLR, always. This counts for both v1 and v2.
x0n
and the cleanest way for version in powershell is probably: [environment]::Version
x0n
+2  A: 

On PowerShell 2.0, just take a peek at the $PSVersionTable variable:

PS> $psversiontable

Name                           Value
----                           -----
CLRVersion                     2.0.50727.4927
BuildVersion                   6.1.7600.16385
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

On PowerShell 1.0, use [System.Environment]::Version:

PS> [Environment]::Version

Major  Minor  Build  Revision
-----  -----  -----  --------
2      0      50727  4927
Keith Hill
A: 

PS > [Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()
C:\Windows\Microsoft.NET\Framework\v2.0.50727\

Shay Levy