'PowerShell Version check prior to script execution
I'm just asking the communitty if they have come across a way to have the a script check what version of POSH is running prior to the execution of the script. Currently, my work around is the following code:
#region Final Checks
#//Check to make sure that version of PowerShell is at least 3.0 before preceding.
If($PSVersionTable.PSVersion.Major -le 2) {
Throw "This script has not been tested with version 2.0 or older of PowerShell. Please execute this script from a system that has PowerShell 3.0 or newer installed. Windows 8/Server 2012 and newer has it installed by default. Windows 7/Server 2008 R2 can be patched to have 3.0 installed."
}
#endregion Final Checks
I have this right after defining my parameters. However, for my own crazy sake, I want the script to preform this check automatically prior to getting into the meat and potato of the script. A good comparison is using Validate[X] for a parameter. If an operator tries to provide data that doesn't fit my user, an error is thrown prior to the execution of the script. Any ideas? I know that there is nothing in [CmdletBinding()] that does it. Thanks!
Solution 1:[1]
You can use #Requires
at the top of your script as a way of telling PowerShell what your script needs to do it's thing.
In your specific case you would put
#Requires -Version 3
This will tell PowerShell that at least PowerShell Version 3 is needed, if someone tries to run the script with PowerShell Version 2 they will receive the following message:
The script 'version3.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:2 + & <<<< C:\Users\testuser\Desktop\version3.ps1 + CategoryInfo : ResourceUnavailable: (version3.ps1:String) [], ScriptRequiresException + FullyQualifiedErrorId : ScriptRequiresUnmatchedPSVersion
In addition to Version you can require other things as well, all of which are listed in about_Requires on TechNet: https://technet.microsoft.com/en-us/library/hh847765.aspx
#Requires -Version 4
#Requires -Module MyCmdlets
Write-Host "If you see this, you are running Version 4 and have the MyCmdlets Module available"
Solution 2:[2]
#Requires was added in PowerShell 5 Will not work in earlier versions.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | user409792 |