Datasheet
UNDERSTAND THE BASICS OF POWERSHELL 31
Administering
Service Delivery
PART I
is speci es that the script will accept a string parameter called
-FirstName
that
gets passed into the
$FirstName
variable inside the script. When the script is run,
the user executes it with the following command:
MyScript.ps1 -FirstName Brenna
Use Positional Parameters
When using a parameter as a positional parameter, you need to specify the parame-
ter’s position in the parameter declaration. Expanding on the previous example, the
following command declares the
FirstName
parameter as a positional parameter
that is accepted as the rst parameter in the script’s command:
param([Parameter(Position=0)][string]$FirstName)
When the user runs the script, the
FirstName
parameter can be speci ed as either
a positional or a named parameter. Because we included the name of the parameter
in addition to its position, both commands are valid.
Other Parameter Settings
You should be aware of a couple of other parameter settings. Optionally, you can
specify a default value for a parameter in case the user decides not to pass a value
in. e following parameter declaration assigns a default value of
Ben
to the
FirstName
parameter:
param([string]$FirstName = “Ben”)
You can also decide whether a parameter is mandatory for the script or whether
it’s optional. To declare a parameter as mandatory, set the
mandatory
property
to
$true
in the script’s parameter declaration. e following example sets the
FirstName
parameter as mandatory:
param([Parameter(Mandatory=$true)][string]$FirstName)
ere are many other properties that you can set for a parameter as well. Table 1.7
describes some of the common properties that you might use when writing your
PowerShell Scripts.
c01.indd 31c01.indd 31 5/12/2011 1:07:51 PM5/12/2011 1:07:51 PM