【问题标题】:PowerShell Version check prior to script execution脚本执行前的 PowerShell 版本检查
【发布时间】:2016-03-22 22:15:19
【问题描述】:

我只是在询问社区是否有办法让脚本在执行脚本之前检查正在运行的 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()] 中没有任何东西可以做到这一点。谢谢!

【问题讨论】:

    标签: powershell powershell-3.0 powershell-ise


    【解决方案1】:

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

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

    #Requires -Version 3
    

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

    脚本“version3.ps1”无法运行,因为它在 Windows PowerShell 3.0 版的第 1 行包含“#requires”语句。脚本所需的版本与当前运行的 Windows PowerShell 版本 2 版本不匹配 .0. 在行:1 字符:2 + &

    除了 Version 你还可以要求其他东西,所有这些都列在 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"
    

    【讨论】:

    • 神圣的蝙蝠侠!我不得不说他们在每个版本中都不断地在 POSH 中添加很棒的东西。这行得通,感谢您的出色回答。我完全不知道#Requires,因为我真的没有过多地涉足清单。现在我把它添加到我的工具箱中。我真的希望我能再投票三次,因为你的答案有例子、参考和很好的解释。快乐的脚本!
    • 很高兴我能帮上忙 :)
    猜你喜欢
    • 2018-11-17
    • 2013-03-25
    • 1970-01-01
    • 2021-04-11
    • 2014-01-06
    • 2018-06-10
    • 1970-01-01
    • 2021-11-06
    • 2012-09-18
    相关资源
    最近更新 更多