Validating your parameters are important. This quick tip is about integer parameters.
As you probably know, there are different types of integer types, but the most common one in use are probably System.Int32. Validating any parameters that use integer parameters are smart, so you don’t get any angry error messages in your script because the value is outside the value range of the type.
The following table shows the different integer types and their minimum and maximum values:
|Type Name||Minimum Value||Maximum Value|
Note! When you use [Int] it’s [System.Int32] you are using.
Often you might see this kind of parameter declaration for integers:
[Parameter()] [ValidateRange(-2147483648,2147483647)] [int] $ValueX
This is of course correct, but typically you don’t want negative values and you might rewrite it into this:
[Parameter()] [ValidateRange(0,2147483647)] [int] $ValueX
But as you can see from my table above, if you only want positive values, you could have used an unsigned integer instead, as these have a minimum value of 0.
But did you know that the all the integer types have two fields called ‘MinValue’ and ‘MaxValue’? These can be used to show, you guessed it, the minimum and maximum values of the type. So the two above examples can be rewritten further like this:
[Parameter()] [ValidateRange([int]::MinValue,[int]::MaxValue)] [int] $ValueX [Parameter()] [ValidateRange(0,[int]::MaxValue)] [int] $ValueY
So now you don’t have to memorize the maximum values of the int type anymore (or more usually, look it up online), just use the MinValue/MaxValue fields!