about_Functions_Advanced_Parameters

適用於: Windows PowerShell 2.0, Windows PowerShell 3.0, Windows PowerShell 4.0, Windows PowerShell 5.0

主題

在此插入區段主體。

簡短描述

說明如何將參數加入進階函式。

詳細描述

您可以將參數加入您撰寫的進階函式,並可使用參數屬性和引數,限制函式使用者對該參數送出的參數值。

不只是 Windows PowerShell® 自動加入所有 Cmdlet 和進階函式的一般參數,您加入函式的參數也可供使用者使用。如需 Windows PowerShell 一般參數的詳細資訊,請參閱 about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216)。

從 Windows PowerShell 3.0 開始,您可以使用具有 @Args 的展開來代表命令中的參數。這項技術對於簡單與進階函式有效。如需詳細資訊,請參閱 about_Functions (https://go.microsoft.com/fwlink/?LinkID=113231) 和 about_Splatting (https://go.microsoft.com/fwlink/?LinkID=262720)。

靜態參數

靜態參數是一律可在函式中使用的參數。在 Windows PowerShell Cmdlet 和指令碼中的大多數參數都是靜態參數。

下列範例顯示 ComputerName 參數的宣告,其具有下列特性:

它是強制性的 (必要)。

它會從管線接收輸入。

它會接受字串陣列做為輸入。

        Param
          (
            [parameter(Mandatory=$true,
            ValueFromPipeline=$true)]
            [String[]]
            $ComputerName
          )

參數的屬性

本章描述您可以加入函式參數的屬性。

所有屬性都是選擇性的。不過,如果您省略 CmdletBinding 屬性,然後使其識別為進階函式,則此函式必須包含 Parameter 屬性。

您可以在每個參數宣告中加入一個或多個屬性。您可以加入參數宣告的屬性數目沒有限制。

Parameter 屬性

Parameter 屬性用來宣告函式參數的屬性。

Parameter 屬性是選擇性的,如果沒有任何函式的參數需要屬性,則您可以省略該屬性,但若要將函式辨識為進階的函式 (而不是簡單的函式),則函式必須具有 CmdletBinding 屬性或 Parameter 屬性,或兩者兼具。

Parameter 屬性有定義參數特性的引數,例如定義該參數是強制性或選擇性。

使用下列語法以宣告 Parameter 屬性、引數,以及引數值。括住引數的括弧和其值必須跟在 "Parameter" 後面,並且沒有任何空格。

        Param
          (
            [parameter(Argument=value)]
            $ParameterName
          )

使用逗號來分隔括弧內的引數。使用下列語法來宣告 Parameter 屬性的兩個引數。

        Param
          (
            [parameter(Argument1=value1,
                       Argument2=value2)]

          )

如果您使用不含引數的 Parameter 屬性 (當做使用 CmdletBinding 屬性的替代方式),則仍然需要屬性名稱後面的括弧。

        Param
          (
            [parameter()]
            $ParameterName
          )

Mandatory 引數

Mandatory 引數表示該參數是必要的。如果未指定這個引數,則該參數是選擇性參數。

下列範例會宣告 ComputerName 參數。它會使用 Mandatory 引數使其成為強制參數。

        Param
          (
            [parameter(Mandatory=$true)]
            [String[]]
            $ComputerName
          )

Position 引數

在命令中使用參數時,Position 引數會決定是否需要參數名稱。當參數宣告包含 Position 引數時,此參數名稱可以省略,且 Windows PowerShell 會依據在此命令中未命名參數值清單的位置 (或順序),識別未命名參數值。

如果未指定 Position 引數,則每當在命令中使用參數時,此參數名稱 (或參數名稱的別名或縮寫) 必須位於參數值之前。

根據預設,所有函式參數都有位置性。Windows PowerShell 會指派位置數字給參數,其順序為在此函式中宣告參數的順序。若要停用這項功能,請將 CmdletBinding 屬性的 PositionalBinding 引數值設為 $False。對於在參數上宣告的引數,Position 引數會優先於 PositionalBinding 引數值。如需詳細資訊,請參閱 about_Functions_CmdletBindingAttribute 中的 PositionalBinding。

Position 引數的值會以整數指定。位置值為 0 代表命令中的第一個位置、位置值為 1 代表命令中的第二個位置,依此類推。

如果函式沒有位置參數,則 Windows PowerShell 會根據宣告參數的順序,指派位置給每個參數。不過,最佳做法是勿依賴此指派方式。當您想要參數具有位置性時,請使用 Position 引數。

下列範例會宣告 ComputerName 參數。這會使用數值為 0 的 Position 引數。因此,當命令中省略 "-ComputerName" 時,其值必須為該命令中的第一個,或只能是未命名參數值。

        Param
          (
            [parameter(Position=0)]
            [String[]]
            $ComputerName
          )

注意:

當 Get-Help Cmdlet 顯示對應的 "Position?" 參數屬性時,此位置值會遞增 1。例如,Position 引數值為 0 的參數具有參數屬性 "Position?1"。

ParameterSetName 引數

ParameterSetName 引數會指定參數所屬的參數集。如果未不指定任何參數集,則此參數屬於此函式所定義的所有參數集。因此,若要保持唯一,每個參數集必須具有至少一個不是任何其他參數集成員的參數。

下列範例會宣告 Computer 參數集的 ComputerName 參數、User 參數集的 UserName 參數,和這兩個參數集內的 Summary 參數。

        Param
          (
            [parameter(Mandatory=$true,
                      ParameterSetName="Computer")]
            [String[]]
            $ComputerName,

            [parameter(Mandatory=$true,
                      ParameterSetName="User")]
            [String[]]
            $UserName,

            [parameter(Mandatory=$false)]
            [Switch]
            $Summary
          )

您只能在每個引數中指定一個 ParameterSetName 值,且在每個 Parameter 屬性中只能指定一個 ParameterSetName 引數。若要表示參數出現在一個以上的參數集,請加入額外的 Parameter 屬性。

下列範例明確地將 Summary 參數加入 Computer 和 User 參數集。Summary 參數在一個參數集為強制性,而在其他參數集則為選擇性。

        Param
          (
            [parameter(Mandatory=$true,
                      ParameterSetName="Computer")]
            [String[]]
            $ComputerName,

            [parameter(Mandatory=$true,
                      ParameterSetName="User")]
            [String[]]
            $UserName,

            [parameter(Mandatory=$false, ParameterSetName="Computer")]
            [parameter(Mandatory=$true, ParameterSetName="User")]
            [Switch]
            $Summary
          )
        

如需參數集的詳細資訊,請參閱 MSDN 文件庫中的<Cmdlet 參數集>,網址是 https://go.microsoft.com/fwlink/?LinkId=142183。

ValueFromPipeline 引數

ValueFromPipeline 引數表示該參數接受來自管線物件的輸入。如果函式接受整個物件,而不只是物件的屬性,請指定這個引數。

下列範例會將 ComputerName 參數宣告為強制性,並接受從管線傳遞至函式的物件。

        Param
          (
            [parameter(Mandatory=$true,
                      ValueFromPipeline=$true)]
            [String[]]
            $ComputerName
          )
ValueFromPipelineByPropertyName 引數

ValueFromPipelineByPropertyName 引數表示參數接受來自管線物件屬性的輸入。此物件屬性必須和該參數具有相同的名稱或別名。

例如,如果函式具有 ComputerName 參數,且傳送的物件具有 ComputerName 屬性,則會將 ComputerName 屬性的值指派給該函式的 ComputerName 參數。

下列範例會宣告 ComputerName 參數為強制性,並接受透過管線傳遞至函式物件之 ComputerName 屬性的輸入。

        Param
          (
            [parameter(Mandatory=$true,
                      ValueFromPipelineByPropertyName=$true)]
            [String[]]
            $ComputerName
          )

ValueFromRemainingArguments 引數

ValueFromRemainingArguments 引數表示此參數接受該命令中的所有參數值,這些參數值不會指派給此函式的其他參數。

下列範例會宣告 ComputerName 參數為強制性,並接受已送出至函式的所有其餘參數值。

        Param
          (
            [parameter(Mandatory=$true,
                      ValueFromRemainingArguments=$true)]
            [String[]]
            $ComputerName
          )

HelpMessage 引數

HelpMessage 引數會指定包含其值或參數簡短描述的字串。Windows PowerShell 會在提示中顯示訊息,會在命令中遺失強制參數值的時候顯示該訊息。此引數不會影響選擇性參數。

下列範例會宣告強制的 ComputerName 參數,和說明預期參數值的說明訊息。

        Param
          (
            [parameter(mandatory=$true,
                       HelpMessage="Enter one or more computer names separated by commas.")]
            [String[]]
            $ComputerName
          )

ALIAS 屬性

Alias 屬性會建立參數的替代名稱。您可指派給參數的別名數目沒有任何限制。

下列範例顯示的參數宣告會將 "CN" 和 "MachineName" 別名加入強制的 ComputerName 參數。

        Param
          (
            [parameter(Mandatory=$true)]
            [alias("CN","MachineName")]
            [String[]]
            $ComputerName
          )

Parameter 和 Variable 驗證屬性

驗證屬性會指示 Windows PowerShell 測試參數值,這些參數值為使用者呼叫進階函式時所送出。如果參數值無法通過測試,則會產生錯誤,而且不會呼叫此函式。您也可以使用一些驗證屬性來限制使用者可以指定變數的值。

AllowNull 驗證屬性

AllowNull 屬性允許讓強制參數的值為 null ($null)。下列範例會宣告可以具有 Null 值的 ComputerName 參數。

        Param
          (
            [parameter(Mandatory=$true)]
            [AllowNull()]
            [String]
            $ComputerName
          )
AllowEmptyString 驗證屬性

AllowEmptyString 屬性允許強制參數的值為空字串 ("")。下列範例會宣告可以具有空白字串值的 ComputerName 參數。

        Param
          (
            [parameter(Mandatory=$true)]
            [AllowEmptyString()]
            [String]
            $ComputerName
          )
AllowEmptyCollection 驗證屬性

AllowEmptyCollection 屬性允許強制屬性的值為空集合 (@())。下列範例會宣告可以具有空集合值的 ComputerName 參數。

        Param
          (
            [parameter(Mandatory=$true)]
            [AllowEmptyCollection()]
            [String[]]
            $ComputerName
          )
ValidateCount 驗證屬性

ValidateCount 屬性指定參數接受之參數值的最小和最大數目。Windows PowerShell 如果呼叫函式之命令的參數值數字超出範圍,則會產生錯誤。

下列參數宣告建立 ComputerName 參數,可接受 1 到 5 的參數值。

        Param
          (
            [parameter(Mandatory=$true)]
            [ValidateCount(1,5)]
            [String[]]
            $ComputerName
          )
ValidateLength 驗證屬性

ValidateLength 屬性可指定參數或變數值中字元的數目下限及上限。Windows PowerShell 如果對參數或變數指定的值超出範圍,則會產生錯誤。

在下列範例中,每個電腦名稱必須有 10 個字元。

        Param
          (
            [parameter(Mandatory=$true)]
            [ValidateLength(1,10)]
            [String[]]
            $ComputerName
          )

在下列範例中,變數 $number 的值必須是最少一個字元的長度,而上限為 10 個字元。

        [Int32][ValidateLength(1,10)]$number = 01
ValidatePattern 驗證屬性

ValidatePattern 屬性會指定和參數或變數值比較的規則運算式。Windows PowerShell 如果值不符合規則運算式,則會產生錯誤。

在下列範例中,參數值必須是四位數的數字,而且每一個數字必須是 0 到 9 的數字。

        Param
          (
            [parameter(Mandatory=$true)]
            [ValidatePattern("[0-9][0-9][0-9][0-9]")]
            [String[]]
            $ComputerName
          )

在下列範例中,$number 變數的值必須是四位數的數字,而且每一個數字必須是 0 到 9 的數字。

        [Int32][ValidatePattern("[0-9][0-9][0-9][0-9]")]$number = 1111
ValidateRange 驗證屬性

ValidateRange 屬性會指定每個參數或變數值的數值範圍。Windows PowerShell 如果有任何變數超出該範圍,則會產生錯誤。在下列範例中,Attempts 參數的值必須介於 0 和 10 之間。

        Param
          (
            [parameter(Mandatory=$true)]
            [ValidateRange(0,10)]
            [Int]
            $Attempts
          )

在下列範例中,變數 $number 的值必須介於 0 和 10 之間。

        [Int32][ValidateRange(0,10)]$number = 5
ValidateScript 驗證屬性

ValidateScript 屬性會指定用來驗證參數或變數值的指令碼。Windows PowerShell 如果指令碼傳回 "False" 或擲回例外狀況,則會傳送該值給指令碼,並產生錯誤。

當您使用 ValidateScript 屬性時,會將要進行驗證的值對應至 $_ 變數。您可以使用 $_ 變數來參考指令碼中的值。

在下列範例中,EventDate 參數的值必須大於或等於目前的日期。

        Param
          (
            [parameter()]
            [ValidateScript({$_ -ge (get-date)})]
            [DateTime]
            $EventDate
          )

在下列範例中,變數 $date 的值必須大於或等於目前的日期和時間。

       [DateTime][ValidateScript({$_ -ge (get-date)})]$date = (get-date)
ValidateSet 屬性

ValidateSet 屬性會指定一組有效的參數或變數值。Windows PowerShell 如果參數或變數不符合此集合中的值,則會產生錯誤。在下列範例中,Detail 參數的值只能是 "Low"、"Average" 或 "High"。

        Param
          (
            [parameter(Mandatory=$true)]
            [ValidateSet("Low", "Average", "High")]
            [String[]]
            $Detail
          )

在下列範例中,變數 $flavor 的值必須是 Chocolate、Strawberry 或 Vanilla。

        [String][ValidateSet("Chocolate", "Strawberry", "Vanilla")]$flavor = Strawberry
ValidateNotNull 驗證屬性

ValidateNotNull 屬性會指定參數值不能是 null ($null)。Windows PowerShell 如果該參數值為 null,則會產生錯誤。

ValidateNotNull 屬性旨在用於未指定參數值類型或指定的類型將接受 Null 值時。(如果您指定不接受 null 值的類型,例如字串,則沒有 ValidateNotNull 屬性的 null 值將會遭到拒絕,因為它不符合指定的類型。)

在下列範例中,ID 參數的值不可為 null。

        Param
          (
            [parameter(Mandatory=$true)]
            [ValidateNotNull()]
            $ID
          )
ValidateNotNullOrEmpty 驗證屬性

ValidateNotNullOrEmpty 屬性指定參數值不得為 null ($null),也不能為空字串 ("")。如果在函式呼叫中使用此參數,但其值為 null、空字串或空陣列,則 Windows PowerShell 會產生錯誤。

        Param
          (
            [parameter(Mandatory=$true)]
            [ValidateNotNullOrEmpty()]
            [String[]]
            $UserName
          )

動態參數

動態參數是只在特定情況下可用之 Cmdlet、函式或指令碼的參數。

例如,許多提供者 Cmdlet 具有的參數,是僅當 Cmdlet 用於提供者磁碟機內,或用於提供者磁碟機的特定路徑才可使用的參數。例如,只有當 Encoding 參數用在檔案系統磁碟機時,才可在 Add-Content、Get-Content 和 Set-Content Cmdlet 上使用。

您也可以建立一個參數,只有在函式命令中使用另一個參數時,或另一個參數具有特定值時,才會出現您建立的參數。

動態參數可以非常有用,但因為對使用者而言很難探索,所以只在必要時才使用。若要尋找動態參數,使用者必須位於提供者路徑中、使用 ArgumentList Get-Command Cmdlet 參數,或使用 Get-help 的 Path 參數。

若要建立函式或指令碼的動態參數,請使用 DynamicParam 關鍵字。

語法如下:

      DynamicParam {<statement-list>}

在陳述式清單中,使用 If 陳述式來指定參數在函式中可用的條件。

請使用 New-Object Cmdlet 來建立 System.Management.Automation.RuntimeDefinedParameter 物件,藉此代表參數並指定其名稱。

您也可以使用 New-Object 命令來建立 System.Management.Automation.ParameterAttribute 物件,藉此代表參數的屬性,例如 Mandatory、Position 或 ValueFromPipeline 或其參數集。

下列範例顯示的範例函式具有名為 Name 和 Path 的標準參數和名為 DP1 的選擇性動態參數。DP1 參數位於 PSet1 參數集合中,且具有 Int32 類型。只有當在 Path 參數的值包含 "HKLM:",表示 HKEY_LOCAL_MACHINE 登錄磁碟機正在使用它的時候,DP1 參數才可在 Sample 函式中使用。

    function Get-Sample {
        [CmdletBinding()]
        Param ([String]$Name, [String]$Path)
 
        DynamicParam
        {
            if ($path -match ".*HKLM.*:")
            {
                $attributes = new-object System.Management.Automation.ParameterAttribute
                $attributes.ParameterSetName = "__AllParameterSets"
                $attributes.Mandatory = $false
                $attributeCollection = new-object `
                    -Type System.Collections.ObjectModel.Collection[System.Attribute]
                $attributeCollection.Add($attributes)

                $dynParam1 = new-object `
                    -Type System.Management.Automation.RuntimeDefinedParameter("dp1", [Int32], $attributeCollection)
            
                $paramDictionary = new-object `
                    -Type System.Management.Automation.RuntimeDefinedParameterDictionary
                $paramDictionary.Add("dp1", $dynParam1)
                return $paramDictionary
            }
        }
    }

如需詳細資訊,請參閱 MSDN (Microsoft Developer Network) 文件庫中的<RuntimeDefinedParameter 類別>,網址為 https://go.microsoft.com/fwlink/?LinkID=145130。

Switch 參數

Switch 參數是沒有參數值的參數。只有在使用該參數時,才會有效,而且只有一種作用。

例如,PowerShell.exe 的 -NoProfile 參數是切換參數。

若要在函式中建立切換參數,請指定參數定義中的 Switch 類型。

    For example:
        Param ([Switch]<ParameterName>)
    -or- 
        Param
          (
             [parameter(Mandatory=$false)]
             [Switch]
             $<ParameterName>
          )

切換參數非常容易使用,且比起語法更困難的布林參數更常被使用。

例如,若要使用切換參數,使用者要輸入命令中的參數。

        -IncludeAll

若要使用布林參數,使用者要輸入參數和一個布林值。

        -IncludeAll:$true

在建立切換參數時,請小心選擇參數名稱。請確定參數名稱可傳達參數作用給使用者,並避免模稜兩可的詞彙,例如 Filter 或 Maximum,這可能會暗示某些值是必要的。

另請參閱

about_Functions

about_Functions_Advanced

about_Functions_Advanced_Methods

about_Functions_CmdletBindingAttribute

about_Functions_OutputTypeAttribute