How to ensure that we use powershell 2.0?

We provide scripts for clients who will work only in Powershell 2.0.

With the command, we can provide the installation of powershell 2.0, as shown below

$version = Get-host | Select-object Version 

But if we provide a script, how to ensure that this is done from Powershell 2.0?

When executing a script, Powershell 2.0 functions may give script errors when the script itself is run. It's not him?

+8
powershell
source share
4 answers

You can annotate your script with #requires and state that it should not work on anything less than PowerShell v2:

 #requires -Version 2.0 

(Note: This is surprisingly hard to find, even if you dimly know that it exists.)

+11
source share

Based on the host version, this is not the safest thing, since the script can be run on hosts that do not have the same host version as the PowerShell version.

The variable $ PSVersionTable has been added to the v2 variable. You can check if a variable exists, if it works v2 and higher, you can also check the PSVersion.Major property:

 if($PSVersionTable) { 'PowerShell {0}' -f $PSVersionTable.PSVersion.Major } else { 'PowerShell 1' } 
+2
source share

I would do something like this:

 # get version $ver = $PsVersionTable.psversion.major # Check to see if it V2 If ($ver -NE 2) {"incorrect version - exiting; return} # Everything that follows is V2 

Hope this helps!

+2
source share

Try using $PSVersionTable

You will get something like:

  Name Value ---- ----- CLRVersion 2.0.50727.5456 BuildVersion 6.1.7601.17514 PSVersion 2.0 WSManStackVersion 2.0 PSCompatibleVersions {1.0, 2.0} SerializationVersion 1.1.0.1 PSRemotingProtocolVersion 2.1 
0
source share

All Articles