Using The PowerShell ValidateSet Parameter Attribute

PowerShell parameter validation is a powerful feature. One of those features is the ValidateSet attribute. This parameter validation feature allows you to ensure a user only provides a value that you require in a particular set of values as input to a function. Josh will cover this in detail.

Powershell's validate set validation attribute allows you to specify a collection of values which your parameters or variables will accept and this example function. I'm using the validate set attribute within square brackets to define a collection of integers, which my value in parameter will accept. This collection is defined within parentheses. When I run this function specifying an integer that is within my valid set, the function complete successfully. If however, I specify an integer dead isn't part of that set of valid values. I get an error helpfully reminding me which values are in that set of valid values. It's also possible to use this attribute outside of functions to validate the values being provided to a variable. To do that, you define the validate set attribute within square brackets and then within parentheses. You define your set of valid values in this case, the strings, Android and iPhone. Then you define the name of your variable in this case phone and then you can assign a value to it. In this example, we doing it via read host to ask for input at the console. When I run this, if I type Android, it completes successfully without error. If however, I run this and tell a lie and say that I'm using a Windows Phone. I get an error because that value isn't in my set of valid values notice, however, that the error message here isn't as user friendly as the one that you get. When you do this viewer function because I'm not being told what the valid set actually is. That's been the validate set attribute thank you for watching.