Using The PowerShell ValidateCount Parameter Attribute

Sometimes it’s just not good enough to let a user pass whatever they want into a PowerShell function. That’s what we have Josh King for; the undisputed PowerShell parameter validation attribute champ. In this video, Josh is able to show us how he can limit parameter input by a certain number of elements. Nice, Josh. Your job here is done.

Powershell's validate count validation attribute allows you to specify the minimum and maximum number of values that a collection will accept in this example function. I'm using the validate count attribute within square brackets to define how many strings mystring collection parameter will accept. As you can see with them. These parentheses by minimum count is 2 and my maximum count is 3. If I run this function with only one argument untold that I provided fewer than the minimum number of arguments and that I should provide more than 2. If I do provide to the function runs successfully and if I provide 4 arguments. I get an error stating that the number of provided arguments exceeds my maximum allowed arguments. It's also possible to use the validate count validation attribute outside of functions directly against variables to do so again, you define the attribute within square braces and within the parentheses. You define the minimum and maximum number of values that your collection will accept. In this example and my first script array. I'm giving to define the array with 3 values. However, my validate count will only allow one or 2 values and I'm told that it's not valid. However, if I get rid of the third value complete successfully and if I look at that array I can see the contents of it. And my second script are a defining that it's valid to have zero values in the array and up to 2 values. So I'm able to define this as an empty array. And I'm able to add item store. If I look at this array, I can see the values that if I go to add a third value as this is exceeding my maximum allowed count I get an error. And that's the validate count validation attribute thank you for watching.