about_requires
主题
about_Requires
简短说明
通过要求使用指定的管理单元和版本来阻止脚本运行。
详细说明
除非满足 Windows PowerShell 版本、管理单元和管理单元版本先决条件,否则 #Requires 语句
会阻止脚本运行。如果没有满足先决条件,Windows PowerShell 不会运行脚本。
可在任何脚本中使用 #Requires 语句。但不能在函数、cmdlet 或管理单元中使用这些语句。
语法
使用以下语法可以指定您希望要求使用的管理单元和管理单元版本:
#requires -PsSnapIn <PsSnapIn> [-Version <N>[.<n>]]
使用以下语法可以指定您希望要求使用的最低 Windows PowerShell 版本:
#requires -Version <N>[.<n>]
使用以下语法可以指定您希望要求使用的 shell:
#requires -ShellId <ShellId>
使用规则
- #Requires 语句必须是脚本中某一行上的第一项。
- 一个脚本可以包括多个 #Requires 语句。
- #Requires 语句可以出现在脚本中的任意一行。
示例
以下语句要求使用 Microsoft.PowerShell.Security 管理单元:
#requires -PsSnapIn Microsoft.PowerShell.Security
如果没有加载 Microsoft.PowerShell.Security 管理单元,则脚本不会运行,Windows
PowerShell 将显示以下错误消息:
“无法运行脚本‘<脚本名称>’,因为缺少其‘#requires’语句指定的以下
Windows PowerShell 管理单元: Microsoft.PowerShell.Security。”
以下语句要求使用 Windows PowerShell 2.0 版本或 Microsoft.PowerShell.Security
管理单元的任何更高版本:
#requires -PsSnapIn Microsoft.PowerShell.Security -Version 2
以下语句要求使用 Windows PowerShell 2.0 或更高版本:
#requires -Version 2.0
以下脚本包含两个 #Requires 语句。必须同时满足这两个语句中指定的要求。否则,脚本将不会
运行。每个 #Requires 语句必须是行上的第一项:
#requires –PsSnapIn Microsoft.PowerShell.Security –Version 2
Get-WMIObject WIN32_LogicalDisk | out-file K:\status\DiskStatus.txt
#requires –Version 2
如果指定的 shell ID 与当前的 shell ID 不匹配,以下 #Requires 语句就会阻止脚本运行。
当前的 shell ID 存储在 $ShellId 变量中:
#requires -ShellId MyLocalShell
另请参阅
about_Automatic_Variables
about_Language_Keywords
about_PSSnapins
get-PSSnapin