about_Requires

適用於: Windows PowerShell 4.0, Windows PowerShell 5.0

主題

about_Requires

簡短描述

防止未含必要元素的指令碼執行。

詳細描述

#Requires 陳述式可在符合 Windows PowerShell® 版本、模組、嵌入式管理單元,以及模組和嵌入式管理單元版本等必要條件之前,防止指令碼執行。如果不符合必要條件,Windows PowerShell 就不會執行指令碼。

您可以在任何指令碼中使用 #Requires 陳述式,但無法在函式、Cmdlet 或嵌入式管理單元中使用。

語法

          #Requires -Version <N>[.<n>] 
          #Requires –PSSnapin <PSSnapin-Name> [-Version <N>[.<n>]]
          #Requires -Modules { <Module-Name> | <Hashtable> } 
          #Requires –ShellId <ShellId>
          #Requires -RunAsAdministrator

使用規則

  • - #Requires 陳述式必須是指令碼行的第一個項目。

  • - 一個指令碼可以包含多個 #Requires 陳述式。

  • - #Requires 陳述式可以出現在任何一行指令碼。

參數

  -Version <N>[.<n>]

指定指令碼所需的 Windows PowerShell 最小版本。輸入主要版本號碼和選擇性次要版本號碼。

例如:

        #Requires -Version 3.0
  -PSSnapin <PSSnapin-Name> [-Version <N>[.<n>]]

指定指令碼所需的 Windows PowerShell 嵌入式管理單元。輸入嵌入式管理單元名稱和選擇性版本號碼。

例如:

        #Requires –PSSnapin DiskSnapin -Version 1.2
  -Modules <Module-Name> | <Hashtable>

指定指令碼所需的 Windows PowerShell 模組。輸入模組名稱和選擇性版本號碼。模組參數是在 Windows PowerShell 3.0 中引進的。

如果所需的模組不在目前的工作階段中,Windows PowerShell 會將其匯入。如果無法匯入模組,Windows PowerShell 會擲回終止錯誤。

針對每個模組,使用下列索引鍵輸入模組名稱 (<字串>) 或雜湊表。該值可以是字串和雜湊表的組合。

  • -- ModuleName。此為必要索引鍵。

  • -- ModuleVersion。此為必要索引鍵。

  • -- GUID。此為選擇性索引鍵。

例如,

        #Requires -Modules PSWorkflow, @{ModuleName="PSScheduledJob";ModuleVersion=1.0.0.0}
  -ShellId

指定指令碼所需的殼層。輸入殼層識別碼。

例如,

        #Requires –ShellId MyLocalShell
  -RunAsAdministrator

當這個切換參數新增至您要求的陳述式時,它會指定必須以較高的使用者權限 (以系統管理員身分執行) 啟動指令碼執行所在的 Windows PowerShell 工作階段。

例如,

        #Requires -RunAsAdministrator

範例

下列指令碼包含兩個 #Requires 陳述式。如果不符合這兩個陳述式中指定的需求,就不會執行指令碼。每個 #Requires 陳述式必須是指令碼行的第一個項目:

          #Requires –Modules PSWorkflow
          #Requires –Version 3
          Param
         (
             [parameter(Mandatory=$true)]
             [String[]]
             $Path
         )
         ...

附註

在 Windows PowerShell 3.0 中,Windows PowerShell 核心套件會顯示為使用 InitialSessionState.CreateDefault2 方法啟動之工作階段中的模組,例如在 Windows PowerShell 主控台中啟動的工作階段。否則會顯示為嵌入式管理單元。Microsoft.PowerShell.Core 則例外,該核心一律是嵌入式管理單元。

另請參閱

about_Automatic_Variables

about_Language_Keyword

about_PSSnapins

get-PSSnapin