Lets start looking at validation of parameter values. We have a few options to try
[ValidateCount(1,n)]
[ValidateLength(1,m)]
[ValidatePattern("[A-Z][A-Z]A-Z][0-9]")]
[ValidateRange(0,10)]
[ValidateScript({$_ -lt 4})]
[ValidateSet("red","blue","green")]
[ValidateNotNull()]
[ValidateNotNullOrEmpty()]
lets start with validating a range of values
001
002 003 004 005 006 007 008 |
function test1 {
param ( [int] [validateRange(1,5)] $p1 ) $p1 * 3 } |
We have a simple function that defines 1 parameter – in my recent post showing all of the possible parameters [datatype] referred to the data type we were assigning to the parameter in this case an integer.
We’ll define a valid range of 1-5 for this value
Our function does a simple multiplication to show its working.
As a test
PS> 1..5 | foreach {test1 $_}
3
6
9
12
15
Everything works. what happens if we submit a value outside the allowed range?
PS> 4..7 | foreach {test1 $_}
12
15
test1 : Cannot validate argument on parameter ‘p1’. The 6 argument is greater than the m
aximum allowed range of 5. Supply an argument that is less than 5 and then try the comma
nd again.
At line:1 char:22
+ 4..7 | foreach {test1 <<<< $_}
+ CategoryInfo : InvalidData: (:) [test1], ParameterBindingValidationExcep
tion
+ FullyQualifiedErrorId : ParameterArgumentValidationError,test1
test1 : Cannot validate argument on parameter ‘p1’. The 7 argument is greater than the m
aximum allowed range of 5. Supply an argument that is less than 5 and then try the comma
nd again.
At line:1 char:22
+ 4..7 | foreach {test1 <<<< $_}
+ CategoryInfo : InvalidData: (:) [test1], ParameterBindingValidationExcep
tion
+ FullyQualifiedErrorId : ParameterArgumentValidationError,test1
4 and 5 are accepted but 6 and 7 are rejected.
If we fall outside the lower range
PS> 2..0 | foreach {test1 $_}
6
3
test1 : Cannot validate argument on parameter ‘p1’. The 0 argument is less than the mini
mum allowed range of 1. Supply an argument that is greater than 1 and then try the comma
nd again.
At line:1 char:22
+ 2..0 | foreach {test1 <<<< $_}
+ CategoryInfo : InvalidData: (:) [test1], ParameterBindingValidationExcep
tion
+ FullyQualifiedErrorId : ParameterArgumentValidationError,test1
A simple test that protects the function. Using this supposes we know what the range of values should be