How to ensure that we are using powershell 2.0?

We are providing scripts to clients that will be working only in Powershell 2.0.

Through command we can ensure that powershell 2.0 is installed like below

$version = Get-host | Select-object Version

But if we provide script how to ensure that they are executing it from Powershell 2.0?

When executing the script , Powershell 2.0 features may give script errors while initiating the script itself.Isn't it?


You can annotate your script with #requires and state that it shouldn't run on anything less than PowerShell v2:

#requires -Version 2.0

(Side note: This is surprisingly hard to find even if you know vaguely that it exists.)


Relying on the host version is not the safest thing to do as the script can be run on hosts that do not have the same host version as PowerShell's version.

The $PSVersionTable variable was added in v2. You can check if the variable exists, if it does you're running v2 and above, you can also check PSVersion.Major property:

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

I'd do something like this:

# get version
$ver = $PsVersionTable.psversion.major
 # Check to see if it's V2

If ($ver -NE 2) 
   {"incorrect version - exiting; return}
# Everything that follows is V2

Hope this helps!

链接地址: http://www.djcxy.com/p/29012.html

上一篇: 为什么这个PowerShell脚本如此缓慢? 我如何加快速度?

下一篇: 如何确保我们使用的是PowerShell 2.0?