Using The PowerShell ValidateRange Parameter Attribute

PowerShell parameter validation is a powerful feature. One of those features is the ValidateRange attribute. This parameter validation feature allows you to ensure a user only provides a number that’s in a particular range of numbers as input to a function. Josh will cover this in detail.

Powershell's validate range validation attribute allows you to specify a range of valid values for a given parameter or variable and this example function. I'm using the validate range attribute within square brackets to determine which entities valid for my number parameter. Within these parentheses of defined the lower and upper bounds of my range, making my range from one to 100. If I run this function with the number zero. I'm told that this is below. My minimum allowed range of one if I run it with the number 50. The function runs as expected, and if I supply. The number 101. I get told this is greater than my maximum allowed of 100. It's also possible to use validate range outside of a function to validate the contents or the value being supplied to a variable to do this specify the validate range attribute within square brackets, then within parentheses. You define the lower bounds. An upper bound of your range. Then you define what the variables name should be and then you can assign a value to. In this case notice I'm using letters rather than numbers and my ranges from A to E if I specify a be run successfully. However, if I specify an if I get an error notice that the error message isn't as user friendly as if you were to do this from within a function. Also in this example, my minimum value for the year. Variable is 2018. My maximum value is 2020. If I run this with the value of 2020, but ran successfully. However, if I increase this to 2022. That does not that is the validate range validation attribute. Thank you for watching.