about_Functions_Advanced

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

主題

about_Functions_Advanced

簡短描述

引進作用類似 cmdlet 的進階函式。

詳細描述

進階函式可讓您撰寫函式,其所能執行的作業類似於您可使用 cmdlet 來執行的作業。當您想要快速撰寫函式,而不需要使用 Microsoft .NET Framework 語言來撰寫編譯的 cmdlet 時,進階函式很有幫助。當您想要限制已編譯 cmdlet 的功能,或想要撰寫類似已編譯 cmdlet 的函式時,這些函式也很有用。

撰寫編譯的 cmdlet 與撰寫進階函式有所不同。編譯的 cmdlet 是必須以 .NET Framework 語言 (例如 C#) 撰寫的 .NET Framework 類別。相對地,進階函式是以 Windows PowerShell® 指令碼語言撰寫,與撰寫其他函式或指令碼區塊的方法相同。

進階函式會使用 CmdletBinding 屬性,將其識別為作用類似於 cmdlet 的函式。CmdletBinding 屬性很類似用於編譯的 cmdlet 類別中,將該類別識別為 cmdlet 的 cmdlet 屬性。如需這個屬性的詳細資訊,請參閱 about_Functions_CmdletBindingAttribute。

下列範例顯示的函式會接受名稱,然後使用所提供的名稱來列印問候語。另請注意,此函式會定義包含動詞 (傳送) 和名詞 (問候語) 配對的名稱,類似已編譯 cmdlet 的「動詞-名詞」組。不過,函式不要求有「動詞-名詞」名稱。

        function Send-Greeting
        {
          [CmdletBinding()]
          Param(
              [Parameter(Mandatory=$true)]
              [string] $Name
          )
          Process
          {
            write-host ("Hello " + $Name + "!")
          }
        }

函式的參數會使用 Parameter 屬性來宣告。此屬性可以單獨使用,也可以和 Alias 屬性或數個其他參數驗證屬性併用。如需如何宣告參數 (包括在執行階段新增的動態參數) 之詳細資訊,請參閱 about_Functions_Advanced_Parameters。

上述函數的實際工作會在 Process 區塊中執行,相當於已編譯 cmdlet 用以處理傳遞至 cmdlet 之資料的 ProcessingRecord 方法。此區塊以及 Begin 和 End 區塊的說明,都在 about_Functions_Advanced_Methods 主題中。

進階函式與編譯的 cmdlet 有下列不同:

- 當字串陣列繫結至布林值參數時,進階函式參數繫結不會擲回例外狀況。

- ValidateSet 屬性和 ValidatePattern 屬性不能傳遞具名參數。

- 進階函式不能用於交易。

另請參閱

about_Functions

about_Functions_Advanced_Methods

about_Functions_Advanced_Parameters

about_Functions_CmdletBindingAttribute

about_Functions_OutputTypeAttribute

Windows PowerShell Cmdlet (https://go.microsoft.com/fwlink/?LinkID=135279)