Making Scripts Check for PowerShell Version

Run PowerShell scripts only on certain versions of PowerShell.

John Savill

March 9, 2015

1 Min Read
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.0Write-Output "I'm version 3.0 or above"$PSVersionTable

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

PS C:> .VersionCheck.ps1I'm version 3.0 or aboveName 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.0Windows PowerShellCopyright (C) 2009 Microsoft Corporation. All rights reserved.PS C:> .VersionCheck.ps1.VersionCheck.ps1 : The script 'VersionCheck.ps1' cannot be run because it contained a "#requires" statement at line 1 for Windows PowerShell version 3.0. The version required by the script does not match the currently running version of 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"}

 

About the Author

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like