Foi útil?

Pergunta

How to use the ValidateCount attribute in PowerShell Function?

PowerShellMicrosoft TechnologiesSoftware & Coding

The validateCount attribute in PowerShell function is to validate the length of an array, which means that you can pass the specific number of arguments into the parameter. In the below example we need array should contain a minimum 1 and maximum 4 values when we pass the values. For that, we will write the below script,

Function ValidateArray {
   Param (
      [ValidateCount(1,3)]
      [String[]]$Animals
   )
   return $PSBoundParameters
}

Output

PS C:\> ValidateArray -Animals Cow, Dog, Cat
Key Value
--- -----
Animals {Cow, Dog, Cat}

The above output is valid but when we pass the null or 4 values, it becomes invalid because we have declared an array should have a length between 1 to 3.

PS C:\> ValidateArray -Animals @()
ValidateArray: Cannot validate argument on parameter 'Animals'. The parameter req
uires at least 1 value(s) and no more than 3 value(s) - 0 value(s) were provided.
PS C:\> ValidateArray -Animals Cow, Dog, Cat, Tiger
ValidateArray: Cannot validate argument on parameter 'Animals'. The parameter req
uires at least 1 value(s) and no more than 3 value(s) - 4 value(s) were provided.
raja
Published on 19-Sep-2020 12:49:17
Advertisements
Foi útil?
Não afiliado a Tutorialspoint
scroll top