Difference between revisions of "Windows PowerShell 1.0 Functions"

From Techotopia
Jump to: navigation, search
(Function Parameter Initialization)
(Function Parameter Initialization)
Line 74: Line 74:
  
 
<pre>
 
<pre>
 +
function names ($firstname = "Not Specified", $lastname = "Unknown")
 +
{
 +
  "First name is $firstname"
 +
  "Last name is $lastname"
 +
}
 
</pre>
 
</pre>
  
When executed with insufficient parameters, the default value is assigned:
+
When executed with insufficient parameters, the default values are assigned:
  
 
<pre>
 
<pre>
 +
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
 
</pre>
 
</pre>
  

Revision as of 19:40, 4 December 2008

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 following 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 output 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 ($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 2 "004"
Performing calculation...
8

but the following does not:

</pre> PS C:\Users\Administrator> multiply 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 </pre>

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 ([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 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"