Basically, I need to use validate pattern to validate a few numbers. I need to be able to run .\Myfilename "number" "number" "number" "number" "number" and it should do a few things with those numbers in the script.
An actually example of what I would type is: .\Myfilename 100 100 20 30 50
What I can’t figure out is how to use validatepattern to assure these numbers are integers.
This is what I tried:
Param ([ValidatePattern("\d")] $G1 = 0, $G2= 0, $G3 = 0, $G4 = 0, $G5 = 0)
I also tried:
Param ([ValidatePattern("\d\s\d\s\d\s\d\s\d")] $G1 = 0, $G2= 0, $G3 = 0, $G4 = 0, $G5 = 0)
To no avail… Any help would be appreciated!
>Solution :
I don’t believe a ValidatePattern Attribute is needed in this case, unless there actually is a specific pattern you want the arguments to have. In addition, you don’t need to have one parameter per argument. You can have only one parameter and type constraint it to [int[]] and have the parameter as ValueFromRemainingArguments argument to make sure you’re capturing all inputs.
- Sample script.ps1:
[cmdletbinding()]
param(
[parameter(ValueFromRemainingArguments)]
[int[]]$Numbers
)
$i = 0
foreach($number in $Numbers)
{
[pscustomobject]@{
ArgumentNumber = ($i++)
Input = $Number
IsInt = $Number -is [int]
}
}
- Sample Input and Output:
PS /> ./script.ps1 123 345 567
ArgumentNumber Input IsInt
-------------- ----- -----
0 123 True
1 345 True
2 567 True
And if you were to use an invalid input such as a string:
PS /> ./script.ps1 123 345 567 'asd'
$Error[0].Exception.InnerException.Messagewould be:
Cannot convert value "System.Collections.Generic.List`1[System.Object]" to type "System.Int32[]". Error: "Cannot convert value "asd" to type "System.Int32". Error: "Input string was not in a correct format.""
Side note, using this method the input should always follow one of the following formats:
<int><white space><int><white space><int><white space><int><comma><int><comma><int><comma>
An input that does not follow this syntax will get you an exception.
<int><comma><int><white space><int>, i.e.:123, 345 567
Will get you the following exception:
Cannot convert value "System.Collections.Generic.List`1[System.Object]" to type "System.Int32[]". Error: "Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Int32"."