about_Requires
主題
about_Requires
簡短描述
需要指定的嵌入式管理單元和版本,才能執行指令碼。
完整描述
使用 #Requires 陳述式時,除非符合 Windows PowerShell 版本、嵌入式管理單元
和嵌入式管理單元版本等必要條件,否則指令碼將無法執行。如果不符合必要條件,
Windows PowerShell 就不會執行指令碼。
您可以在任何指令碼中使用 #Requires 陳述式,但是不能在函數、Cmdlet 或嵌入式
管理單元中使用這個陳述式。
語法
請使用下列語法,指定您想要求的嵌入式管理單元或其版本:
#requires -PsSnapIn <PsSnapIn> [-Version <N>[.<n>]]
請使用下列語法,指定您想要求的 Windows PowerShell 最小版本:
#requires -Version <N>[.<n>]
請使用下列語法,指定您想要求的殼層:
#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
下列 #Requires 陳述式在指定的殼層識別碼不符合目前的殼層識別碼時,會讓指
令碼無法執行。目前的殼層識別碼儲存在 $ShellId 變數中:
#requires -ShellId MyLocalShell
請參閱
about_Automatic_Variables
about_Language_Keywords
about_PSSnapins
get-PSSnapin