Datasheet

UNDERSTAND THE BASICS OF POWERSHELL 33
Administering
Service Delivery
PART I
For example, if you were to create a function called
DisplayMessage
that displays
“Hello, Ken!” it would look like the following:
Function DisplayMessage ()
{
Write-Output “Hello, Ken!”
}
In this function, the message that is displayed is hard-coded. When you call the
DisplayMessage
function, it will display the same message every time. You can
modify this behavior by con guring a parameter that the user can pass in.  ere are
two di erent ways to de ne parameters in functions. If you’ve developed scripts or
applications in other languages, then youre probably familiar with de ning param-
eters in functions using the parentheses in function declarations. Here’s an example
of how this might look:
Function DisplayMessage($name)
{
Write-Output “Hello, $name!”
}
is function allows you to pass in the name that you want displayed in the mes-
sage. In the parentheses following the name of the function, we speci ed a variable
called
$name
. By doing this, we told the function that the  rst parameter that we
send to it will be kept in the
$name
variable. You can also add additional variables
for other parameters. When doing so, you need to separate them inside the paren-
theses with commas.
You can also specify parameters on functions using the same method that we
described for using parameters in scripts. Refer to the section “Accept Script
Parameters” earlier in this chapter to learn how to use this method. When you’re
de ning parameters on functions with this method, you follow the same process,
but your parameter declaration happens on the  rst line of the function rather than
the  rst line of the script. For example, the following function uses this method and
is equivalent to the
DisplayMessage
function that we de ned earlier:
Function DisplayMessage
{
param([string]$name)
Write-Output “Hello, $name!”
}
c01.indd 33c01.indd 33 5/12/2011 1:07:52 PM5/12/2011 1:07:52 PM