共用方式為


如何使用腳本驗證引數

這個範例示範如何指定驗證規則,以在執行 Cmdlet 之前,使用腳本來檢查參數引數。 參數的值會以管道傳送至腳本。 腳本必須 $true 針對輸送給它的每個值傳回。

注意

如需定義這個屬性之類別的詳細資訊,請參閱 ValidateScriptAttribute

使用腳本驗證引數

  • 加入 ValidateScript 屬性,如下列程式碼所示。 此範例會為 UserName 參數指定三個可能值的集合。

    [ValidateScript("$_ % 2", ErrorMessage = "The item '{0}' did not pass validation of script '{1}'")]
    [Parameter(Position = 0, Mandatory = true)]
    public int32 OddNumber
    {
       get { return oddNumber; }
       set { oddNumber = value; }
    }
    
    private int32 oddNumber;
    

如需如何宣告這個屬性的詳細資訊,請參閱 ValidateScript 屬性聲明

另請參閱

ValidateScriptAttribute。

ValidateScript 屬性宣告

撰寫 Windows PowerShell Cmdlet