forked from jdhitsolutions/ISEScriptingGeek
-
Notifications
You must be signed in to change notification settings - Fork 0
/
about_Scripting_ValidateNotNullorEmpty.help.txt
64 lines (50 loc) · 4.7 KB
/
about_Scripting_ValidateNotNullorEmpty.help.txt
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
56
57
58
59
60
61
62
63
64
TOPIC
about_ValidateNotNullorEmpty
SHORT DESCRIPTION
A tutorial on using the [ValidateNotNullorEmpty()] parameter validation
attribute.
LONG DESCRIPTION
I've been writing about the different parameter validation attributes
that you can use in your PowerShell scripting. One that I use in
practically every script is [ValidateNotNullorEmpty()]. This validation
will ensure that something is passed as a parameter value. I'm not
talking about making a parameter mandatory; only that if the user decides
to use the parameter that something is passed. Let's look at my demo.
#requires -version 2.0
Param (
[Parameter(Position=0,Mandatory=$True,
HelpMessage="Enter a process name like lsass")]
[ValidateNotNullorEmpty()]
[string]$Name,
[Parameter(Position=1)]
[ValidateNotNullorEmpty()]
[string]$Computername=$env:computername
)
Try {
Get-Process -Name $name -ComputerName $computername -errorAction "Stop" |
Select *,@{Name="Runtime";Expression={(Get-Date)-$_.StartTime}}
}
Catch {
Write-Warning $_.Exception.Message
}
I've used the attribute on both parameters. The first parameter I've also
made mandatory which makes it more likely that something will be entered.
But if not, then the script will fail. I will also get a similar message
if the user forgest to complete the command.
PS C:\Scripts> .\myscript.ps1 -name lsass -computername
Even though I'm using a default value for Computername, as soon as the
parameter is detected PowerShell assumes I'm going to use a different
value.
Validation should work for missing values, a variable that might be null,
or in general anything that is meaningless. However, it won't prevent
something quirky like this:
PS C:\Scripts> $p=" "
PS C:\Scripts> .\demo-ValidateNotNull.ps1 -name $p
WARNING: Cannot find a process with the name " ". Verify the process name
and call the cmdlet again.
The variable, while semantically meaningless to us, is not null or empty
but a string of 1 space. If there's the chance you might run into this
situation then you can add additional validation checks to the parameter.
SEE ALSO
about_Functions_Advanced_Parameters
http://jdhitsolutions.com/blog