Making Scripts Check for PowerShell Version

Making Scripts Check for PowerShell Version

Q. How can I create a PowerShell script that requries a certain version of PowerShell?

A. If you are writing a PowerShell script that requires a certain version of PowerShell an easy way is to use the following:

#Requires -Version 3.0

This example requires version 3.0 or above which means PowerShell v2.0 (such as Windows Server 2003) would not run the script. This can be tested with the basic script below which I save as VersionCheck.ps1:

#Requires -Version 3.0
Write-Output "I'm version 3.0 or above"
$PSVersionTable

If I launch PowerShell I see that it runs as expected:

PS C:\> .\VersionCheck.ps1
I'm version 3.0 or above

Name Value 
---- ----- 
PSVersion 4.0 
WSManStackVersion 3.0 
SerializationVersion 1.1.0.1 
CLRVersion 4.0.30319.34209 
BuildVersion 6.3.9600.17400 
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0} 
PSRemotingProtocolVersion 2.2 

If I now launch PowerShell in version 2 mode and try to run I get the following:

C:\>powershell -version 2.0
Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.

PS C:\> .\VersionCheck.ps1
.\VersionCheck.ps1 : The script 'VersionCheck.ps1' cannot be run because it con
tained a "#requires" statement at line 1 for Windows PowerShell version 3.0. Th
e version required by the script does not match the currently running version o
f Windows PowerShell version 2.0.
At line:1 char:19
+ .\VersionCheck.ps1 <<<<
+ CategoryInfo : ResourceUnavailable: (VersionCheck.ps1:String) [
], ScriptRequiresException
+ FullyQualifiedErrorId : ScriptRequiresUnmatchedPSVersion

There are other options such as manually checking the version of PowerShell and performing other actions such as inspecting the major version, e.g.

if ($PSVersionTable.PSVersion.Major -gt 2)
{
    Write-Output "Yay"
}
else
{
    Write-Output "Boo"
}

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish