Windows PowerShell 1.0 Functions

Revision as of 20:43, 4 December 2008 by Neil (Talk | contribs) (Creating and Calling a Simple Windows PowerShell Function)

Revision as of 20:43, 4 December 2008 by Neil (Talk | contribs) (Creating and Calling a Simple Windows PowerShell Function)

Windows PowerShell functions provide a way to organize scripts and promote re-use of code. They also provide a mechanism for creating custom cmdlets and filters. Windows PowerShell functions are easy to create and simple to use, as will be illustrated in the remainder of this chapter.

Creating and Calling a Simple Windows PowerShell Function

The most basic of Windows PowerShell functions are created using the function keyword followed by the name of the function. Finally, the list of statements to be executed are enclosed in curly braces. For example, the following function simply outputs a string before returning:

function sayhello
{
    "Hello. Welcome to PowerShell Functions"
}

Having created a simple function, it can be called by referencing the function name:

PS C:\Users\Administrator> sayhello
Hello. Welcome to PowerShell Functions

Passing Parameters to a Function

In the preceding example, the function did not expect to be passed any parameters (also known as arguments). These are values which are entered on the command-line along with the function at the point that it is called. Windows PowerShell stores any parameters that were entered along with the function name in a special variable called $args. The $args variable is actually an array object with each parameter assigned to an array element (for more detailed information on working with arrays refer to the chapter entitled Working with Arrays in Windows PowerShell 1.0.

In order to demonstrate the use of the $args variable in the context of Windows PowerShell functions, the following function displays the number of parameters passed into the function, and then multiplies the first two parameters:

function multiply_numbers 
{
   "Number of parameters = " + $args.count
   $args[0] * $args[1]
}

When called with two parameters, the function generates the following output:

PS C:\Users\Administrator> multiply_numbers 4 2
Number of parameters = 2
8

Specifying Named Parameters

In the above example, we relied on the $args array to access any parameters which were passed through the function when it was called. Whilst this apprach works fine for simple functions, it can quickly become confusing as functions become more complex. An alternative mechanism is to declare the expected parameters and assign them variable names by which they may be accessed within the body of the function. This is achieved by placing the expected parameters in parentheses after the function name during the declaration. For example, the following function declares that two parameters are expected when the function is called, and names them "$firstname" and "$lastname" respectively.

function names ($firstname, $lastname) 
{
   "First name is $firstname"
   "Last name is $lastname"
}

With the parameter names specified, the may be passed through to the function in a number of different ways. The simplest way is to allow the function to allocate the parameters base don their position in the command line. For example:

PS C:\Users\Administrator> names john smith
First name is john
Last name is smith

Alternatively, the parameters may be specified using the names, which allows them to be passed in any order. In the following example, the last name parameter is specified before the first name. Because the parameter names are specified, however, the values are still assigned to the correct parameters:

PS C:\Users\Administrator> names -lastname smith -firstname john
First name is john
Last name is smith

Function Parameter Initialization

In addition to allowing function parameters to be specified and assigned names, Windows PowerShell also allows those parameters to be assigned default values which will be assigned if the parameters are omitted when the function is called. The following example extends the names function to define default values for the $firstname and $lastname parameters:

function names ($firstname = "Not Specified", $lastname = "Unknown") 
{
   "First name is $firstname"
   "Last name is $lastname"
}

When executed with insufficient parameters, the default values are assigned:

PS C:\Users\Administrator> names
First name is Not Specified
Last name is Unknown

PS C:\Users\Administrator> names john
First name is john
Last name is Unknown

Specifying Function Parameter Types

By default, if Windows PowerShell receives a parameter which is of the wrong type for the operations performing in the body of a function it will attempt to perform a type conversion to the correct type. For example, The following function multiplies two numbers passed through as arguments:

function multiply_numbers ($val1, $val2) 
{
   "Performing calculation..."
   $val1 * $val2
}

If a string is passed through as a paramater, Windows PowerShell will attempt to convert it to a number. This may or may not be possible depending on the contents of the string. For example the following works:

PS C:\Users\Administrator> multiply_numbers 2 "004"
Performing calculation...
8

but the following does not:

PS C:\Users\Administrator> multiply_numbers 2 "FOUR"
Performing calculation...
Cannot convert value "FOUR" to type "System.Int32". Error: "Input string was not in a correct forma
t."
At line:4 char:11
+    $val1 *  <<<< $val2

Unfortunately, as can be seen from the above error message, the function was allowed to begin executing. It printed out the "Performing calculation..." message before the error was reported on line 3. Clearly it would be advantageous for the function to reject a parameter if it is not of a specified time. This can be achieved by using type casting in the parameter declaration. For example, to force the two parameters for our multiply function to be numbers they could be cast as type [int32]:

function multiply_numbers ([int32] $val1, [int32] $val2) 
{
   "Performing calculation..."
   $val1 * $val2
}

Now when a parameter is specified that is both of the wrong type and unsuitable for conversion to the correct type, the function rejects the parameter immediately without commencing the execution process:

PS C:\Users\Administrator> multiply_numbers 4 "five"
multiply : Cannot convert value "five" to type "System.Int32". Error: "Input string was not in a co
rrect format."
At line:1 char:9
+ multiply  <<<< 4 "five"

Using Functions in a Pipeline

As discussed in previous chapters, Windows PowerShell allows cmdlets to be executed in a sequence, with the results from one cmdlet used as input to the next cmdlet in the pipeline chain. Pipelines are created by separating the cmdlets by the pipe character (|). In order to include a function in a pipeline it is necessary for that function to process the $input variable. This variable contains the results from the previous cmdlet or function in the pipeline. In the following example, a function named filelengths is designed to take the output from the dir cmdlet, iterate through the $input variable and display the name and length of each file:

function filelengths
{
     foreach ($file in $input)
     {
         "Filename: " + $file + " Length: " + $file.length
     }
}

All that remains to test out this function is to pipe a dir command through to it:

PS C:\Users\Administrator> dir *.txt | filelengths
Filename: C:\Users\Administrator\date.txt Length: 162
Filename: C:\Users\Administrator\error.txt Length: 334
Filename: C:\Users\Administrator\filename.txt Length: 16
Filename: C:\Users\Administrator\mydata.txt Length: 30
Filename: C:\Users\Administrator\mydatafile.txt Length: 8
Filename: C:\Users\Administrator\output.txt Length: 1120

Returning from Functions

By default a function will exit when execution reaches the end of the statements in the body. If a function needs to exit before all the statements have been executed (perhaps as the result of some conditional statement) this may be achieved using the return statement.

The return statement may be used to return silently as follows:

function hello ($name)
{
    if ($name -ne "Fred")
    {
         return
    }

    "Hello Fred!"    
}

Alternatively, the return statement can be used to return a value:

function hello ($name)
{
    if ($name -ne "Fred")
    {
         return "Sorry $name, I was looking for Fred!"
    }

    "Hello Fred!"    
}

When executed with the incorrect name as a parameter, the conditional statement will cause the function to output the Sorry message and exit before reaching the "Hello" statement.

PS C:\Users\Administrator> hello john
Sorry john, I was looking for Fred!

Windows PowerShell Function Administration

Functions declared within PowerShell are stored in the function namespace which is mapped to a virtual function: drive. As such, functions can be manipulated and administered much in the same way files in a filesytem are handled. It is possible, for example, to list the multiply function created earlier in this chapter using the dir command:

PS C:\Users\Administrator> dir function:/multiply_numbers

CommandType     Name                                      Definition
-----------     ----                                      ----------
Function        multiply_numbers                          param([int32] $val1, [int32] $val2) "P...

Similarly, the function can be deleted just as a file would be deleted using the rm command. Since we are at the end of the chapter, we can now safely delete the functions created in the preceding sections:

PS C:\Users\Administrator> rm function:/multiply_numbers
PS C:\Users\Administrator> rm function:/names
PS C:\Users\Administrator> rm function:/sayhello
PS C:\Users\Administrator> rm function:/hello
PS C:\Users\Administrator> rm function:/filelengths