gpt4 book ai didi

脚本执行前的 PowerShell 版本检查

转载 作者:行者123 更新时间:2023-12-03 00:48:26 24 4
gpt4 key购买 nike

我只是问社区他们是否已经找到一种方法让脚本在执行脚本之前检查正在运行的 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

在定义我的参数后,我有这个权利。但是,为了我自己的疯狂,我希望脚本在进入脚本的肉和土 bean 之前自动执行此检查。一个很好的比较是使用 Validate[X] 作为参数。如果运算符(operator)尝试提供不适合我的用户的数据,则会在执行脚本之前引发错误。有任何想法吗?我知道 [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"

关于脚本执行前的 PowerShell 版本检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36166262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com