脚本执行前的 PowerShell 版本检查

PowerShell Version check prior to script execution

我只是问社区他们是否找到了一种方法让脚本在执行脚本之前检查 POSH 的版本 运行。目前,我的解决方法是以下代码:

    #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

我在定义参数后就有了这个权利。然而,为了我自己的疯狂,我希望脚本在进入脚本的内容之前自动执行此检查。一个很好的比较是使用 Validate[X] 作为参数。如果操作员试图提供不适合我的用户的数据,则会在执行脚本之前抛出错误。有任何想法吗?我知道 [CmdletBinding()] 中没有任何东西可以做到这一点。谢谢!

您可以在脚本顶部使用 #Requires 来告诉 PowerShell 您的脚本需要做什么。

在你的具体情况下,你会把

#Requires -Version 3

这将告诉 PowerShell 至少需要 PowerShell 版本 3,如果有人试图 运行 脚本PowerShell 版本 2 他们将收到以下消息:

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

除了版本之外,您还可以要求其他东西,所有这些都列在 TechNet 的 about_Requires 中: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"

#Requires 已在 PowerShell 5 中添加,在早期版本中将不起作用。