forked from jdhitsolutions/ISEScriptingGeek
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathabout_Scripting_ValidateCount.help.txt
More file actions
55 lines (41 loc) · 3.59 KB
/
about_Scripting_ValidateCount.help.txt
File metadata and controls
55 lines (41 loc) · 3.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
TOPIC
about_Scripting_ValidateCount
SHORT DESCRIPTION
A brief tutorial on validating parameters by count
LONG DESCRIPTION
Here’s another parameter validation attribute you might want to use in
your PowerShell scripting and functions. If your parameter can take an
array of values, you might want to limit that array to a certain size.
For example, your parameter can take an array of computer names but you
don’t want to process more than 5 for some reason. This is where
[ValidateCount()] comes in to play.
This attribute takes two values, the minimum number of accepted parameter
values and the maximum.
[ValidateCount(1,10)]
[string[]]$Computername
If used, this would mean I would need at least one computername but no
more than 10. You could also set both values the same if you wanted an
exact number:
[ValidateCount(2,2)]
[int[]]$Numbers
Now, I’d have to pass exactly 2 numbers as parameter values. Let’s look
at a more complete example.
#requires -version 2.0
Param (
[Parameter(Position=0,Mandatory=$True)]
[ValidateCount(1,5)]
[string[]]$Name
)
Foreach ($item in $name) {
#display the name in a random color
Write-Host $item -ForegroundColor ([system.consoleColor]::GetValues(
"system.consolecolor") | get-random)
}
This simple script writes each name in a random color, assuming I pass
no more than 5 names.
If I exceed that count, PowerShell will throw a tantrum (I mean exception).
When you use this validation test, be sure your parameter is set to
accept an array of values, e.g. [string[]].
SEE ALSO
about_Functions_Advanced_Parameters
http://jdhitsolutions.com/blog