Wednesday, August 26, 2015

PowerShell - Functions

The basic structure of a PowerShell function is : the Function keyword follows the name of the function, and after that the PowerShell script in braces.

Lets create a simple function to say 'hello' :
function myFunction { write-host("Hello") }

Call function:
myFunction

Function has default variable $args, which may contains array of values:
function myFunction { write-host("Hello " + $args) }

These both calls work fine
myFunction 'world'
myFunction 'world' ' from Power Shell'


This function looks for if we have any values supplied in $args when called
function CheckArgs {
    If ($args -ne $null)
    {
        "Args passed : $args"
    }
    Else
    {
        "No Args passed."
    }
}

CheckArgs 'test' 'test3'

Caculate the sum of all numbers specified in $args
function sum
{
    $sum = 0;

    foreach ($i in $args)
    {
        $sum += $i
    }

    "Total : $sum"
}
sum 1 2 3

We can also use named variables as parameters.

function Add($p1, $p2)
{
    $p1 + $p2
}
Add 1 7

Functions can have default values of parameters, in case if the function is being called without parameter then the default value will be used.

function Add($p1 = 5, $p2 = 10)
{
    $p1 + $p2
}

Add 2  # you will get 12, i.e. for parameter $p2, the default value 10 will be used.
Add 2 50 # you will get 52

We can use explicitly data types with functions parameters. If we put the wrong type of argument we will get error message.
function Add([int]$p1, [int]$p2)
{
    $p1 + $p2
}
Add 2 10
Add 2 'test'

 Here the first call works as expected, while the second call give you the error:
Add : Cannot process argument transformation on parameter 'p2'. Cannot convert value "test" to type "System.Int32". Error: "Input string was not in a correct format."

No comments:

Post a Comment