Datasheet

34 CHAPTER 1
USING POWERSHELL WITH ACTIVE DIRECTORY
Call Functions
If you want to use a function that you’ve de ned in your script, you have to call
the function. To call the function, you simply need to type in the name of the
function, similar to how you might execute a cmdlet in PowerShell. To call the
DisplayMessage
function, you can use the following line in a script:
DisplayMessage “Brenna”
When this line of the script executes, the
DisplayMessage
function is called and
“Brenna”
is passed in as a parameter.  e function will then execute and output
the message “Hello, Brenna!” One important thing to note is that in order to call a
function, the function must be de ned at the beginning of the script. If you attempt
to call a function before it has been de ned, you’ll receive an error because the
function doesn’t exist yet.
e sample script in Listing 1.1 puts these concepts together so you can better under-
stand how to use a function.  is script creates and calls the
DisplayMessage
function used as an example throughout this section.
LISTING 1.1: SayHello.ps1
## File Name: SayHello.ps1
## Description:
## Demonstrates the use of functions by outputting a simple
## hello message.
##
Function DisplayMessage_Paren($name)
{
Write-Host "Hello, $name!"
}
Function DisplayMessage_Param
{
param([string]$name)
Write-Host "Hello, $name!"
}
Write-Host "Calling the function that uses parentheses..."
DisplayMessage_Paren "Lincoln"
Write-Host
Write-Host "Calling the function that uses param..."
DisplayMessage_Param "Nora"
c01.indd 34c01.indd 34 5/12/2011 1:07:52 PM5/12/2011 1:07:52 PM