Windows PowerShell 1.0 Functions

From Techotopia
Revision as of 21:12, 1 February 2016 by Neil (Talk | contribs) (Text replacement - "<google>BUY_WPS</google>" to "<htmlet>powershell</htmlet>")

Jump to: navigation, search
PreviousTable of ContentsNext
The Windows PowerShell 1.0 switch StatementWorking with File Systems in Windows PowerShell 1.0


Purchase and download the full PDF version of this PowerShell eBook for only $8.99


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.


Contents


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 is 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

<google>ADSDAQBOX_FLOW</google> In the preceding example, the function did not expect to be passed any parameters (also known as arguments). These are values that 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 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 that were passed through to the function when it was called. Whilst this approach 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 actual values 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 based on their respective positions 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 allow 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 performed in the body of a function it will attempt to perform a type conversion to the correct type. The following function, for example, multiplies two numbers passed through as arguments:

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

If a string is passed through as a parameter, 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 type before the function starts to do anything. This can be achieved by using type casting in the parameter declaration. For example, to force the two parameters for our multiply_numbers 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_numbers 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

Loading Function Definitions from a Windows PowerShell Script File

Functions are not persistent across Windows PowerShell sessions. In other words, if you define a function from within the Windows PowerShell interactive shell environment and then exit the session, the function will no longer exist in future sessions. One way of quickly re-loading predefined functions is to place them into a script file and then load that script file from within the shell environment. The way this works isn't quite as most people might expect so this issue needs a little explanation. For the purposes of this description, we will create a simple function in a script file called myfunction.ps1 as follows:

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

    "Hello Fred!"    
}

Ordinarily, a script file is loaded and executed simply by referencing the name of the script at the PowerShell prompt. In fact, when this is performed, PowerShell executes the commands in the script and then discards any new settings, functions and variables once the script exists. So executing our myfunction.ps1 script in the usual way isn't actually going to result in the new function being retained in the function namespace of the current session as illustrated below:

PS C:\Users\Administrator> dir function:hello
Get-ChildItem : Cannot find path 'hello' because it does not exist.
At line:1 char:4
+ dir  <<<< function:hello

In order to have the settings, functions and variables from a script file retained, it is necessary to perform a task known as dotting the script file (also known as sourcing in the UNIX and Linux worlds). This is achieved by prefixing the script name with a dot and a space as follows:

PS C:\Users\Administrator> . ./myfunction.ps1
PS C:\Users\Administrator> dir function:hello

CommandType     Name                                      Definition
-----------     ----                                      ----------
Function        hello                                     param($name) if ($name -ne "Fred")...

As illustrated above, the function is now retained in the Windows PowerShell session. This technique applies equally to variables and any other settings that may be included in a script file which is subsequently dotted.

<google>BUY_WPS_BOTTOM</google>