about_Scripting_ValidateCount.help.txt
TOPIC
about_Scripting_ValidateCount SHORT DESCRIPTION A brief tutorial on validating parameters by count LONG DESCRIPTION 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. 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[]]. SEE ALSO about_Functions_Advanced_Parameters http://jdhitsolutions.com/blog |