Powershell Simplified Part 6: Functions

Functions in Powershell scripts work just like you’d expect.

# define a function
function get-capital($country) {
    $htable = @{UK = "London"; Austria = "Vienna"; France = "Paris"}
    if ($htable.ContainsKey($country)) { return $htable[$country] }
    else { return "Not found" }
}

# call the function
$capital = get-capital("Austria")
write-host $capital

One interesting thing about Powershell functions is that anything you ‘leave behind’ will be automatically assigned as return value. If you leave behind more than one piece of information, it will be returned as an array. Thus we can get rid of the ‘return‘ keyword, but it’s much more readable to use it.

# define a function
function get-capital($country) {
    $htable = @{UK = "London"; Austria = "Vienna"; France = "Paris"}
    if ($htable.ContainsKey($country)) { $htable[$country] }
    else { "Not found" }
}

Adding function parameters is use for making sure your function is called with the right params.

function get-capital {
    param (
        [ValidateSet("prod","ppe","dev")]           # must be a value from this set
        [parameter(Mandatory=$false, position=0)]   # assign a position so that arguments can be passed without a parameter name
        [alias("env")]                              # alias for this param
        [string]                                    # param type is string
        $environment = "dev",                       # use a default value if none specified

        [ValidateRange(1,99)]
        [parameter(Mandatory=$true, position=1)]    # note no alias specified
        [string]
        $country,

        [ValidateSet("UK","Austria","France")]      # also see ValidateScript and ValidatePattern
        [parameter(Mandatory=$false, position=2)]   # This param is optional
        [alias("i")]
        [int]
        $id = 42
    )

    $htable = @{UK = "London"; Austria = "Vienna"; France = "Paris"}
    if ($htable.ContainsKey($country)) { return $htable[$country] }
    else { return "Not found" }
}

# different ways to invoke the function
$capital = get-capital -country "France"
$capital = get-capital -env "prod" -country "France"
$capital = get-capital -env "prod" -country "France" -i 9
$capital = get-capital "prod" "France" 9

For more advanced parameter options see here. Let’s take a look at two more advanced parameter options: switch and pipeline-aware.

function get-capital { param ( # receive incoming pipeline input and bind to this arg [parameter(Mandatory=$true, ValueFromPipeline=$true)] [string] $env, # switch parameters do not take arguments - they are either present or not [switch] $flag ) # check for the presence of 'flag' in the param list if ($flag) { write-host "has flag" } else { write-host "no flag" } write-host $env } get-capital -env "Prod" # 'flag' is optional get-capital -env "Prod" –flag # using the 'flag' param (no param) "PPE" | get-capital # pipe the string value to the function which binds it to $env

Advertisements

About soumya chattopadhyay
I live and work in Seattle, WA. I work with Microsoft technologies, and I'm especially interested in C#.

One Response to Powershell Simplified Part 6: Functions

  1. Pingback: Powershell Simplified Series « I.Net

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: