Here's another parameter validation attribute you might want to use in your PowerShell scripting and functions. If your parameter can take an array of values, you might want to limit that array to a certain size. For example, your parameter can take an array of computer names but you don't want to process more than 5 for some reason. This is where [ValidateCount()] comes in to play.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
This attribute takes two values, the minimum number of accepted parameter values and the maximum.
[ValidateCount(1,10)]
[string[]]$Computername
If used, this would mean I would need at least one computername but no more than 10. You could also set both values the same if you wanted an exact number:
[ValidateCount(2,2)]
[int[]]$Numbers
Now, I'd have to pass exactly 2 numbers as parameter values. Let's look at a more complete example.
#requires -version 2.0
Param (
[Parameter(Position=0,Mandatory=$True)]
[ValidateCount(1,5)]
[string[]]$Name
)
Foreach ($item in $name) {
#display the name in a random color
Write-Host $item -ForegroundColor ([system.consoleColor]::GetValues("system.consolecolor") | get-random)
}
This simple script writes each name in a random color, assuming I pass no more than 5 names.
If I exceed that count, PowerShell will throw a tantrum (I mean exception).
When you use this validation test, be sure your parameter is set to accept an array of values, e.g. [string[]]. If you'd like to try out my sample code feel free to download Demo-ValidateCount.
1 thought on “PowerShell Scripting with [ValidateCount]”
Comments are closed.