如何在 PowerShell 函式中使用 ValidateRange 屬性?
驗證引數是在 PowerShell 變數上定義的一組規則,它限制使用者輸入某些值,並強制使用者輸入特定域中的值。如果沒有驗證引數,則指令碼將很長。ValidateRange 屬性就是其中之一。
ValidateRange 屬性
此引數用於驗證特定數字範圍。例如,如果我們需要使用者輸入 5 到 100 之間的值,我們只需使用 If/else 語句編寫指令碼,如下所示。
function AgeValidation { param( [int]$age ) if(($age -lt 5) -or ($age -gt 100)) { Write-Output "Age should be between 5 and 100" } else{ Write-Output "Age validated" } }
輸出−
PS C:\> AgeValidation -age 4 Age should be between 5 and 100 PS C:\> AgeValidation -age 55 Age validated
上面的程式碼可以正常工作,但我們根本不需要使用者輸入錯誤的年齡,並在使用者輸入錯誤的年齡時丟擲錯誤。這可以透過再次編寫幾行程式碼來實現,但透過 validaterange,我們可以在不編寫更多行的情況下實現我們的目標。
function AgeValidation { param( [ValidateRange(5,100)] [int]$age ) Write-Output "Age validated!!!" }
輸出−
PS C:\> AgeValidation -age 3 AgeValidation: Cannot validate argument on parameter 'age'. The 3 argument is les s than the minimum allowed range of 5. Supply an argument that is greater than or equal to 5 and then try the command again.
PS C:\> AgeValidation -age 150 AgeValidation: Cannot validate argument on parameter 'age'. The 150 argument is g reater than the maximum allowed range of 100. Supply an argument that is less than or equal to 100 and then try the command again.
當輸入低於或高於允許值時,指令碼將丟擲錯誤。這就是我們如何使用ValidateRange 屬性。
廣告