PowerShell Functions II – Output function results as a hash table

In a previous post I wrote a butt-simple function with three parameters, called it a couple ways, and talked about how the function returns its data either as a single string or as an array of variables. Before leaving this, I’m going to experiment about returning data as a hash table.

function Get-ReallySimple($fname,$lname,$age) {

$OutTable=@{"FirstName"=$fname;"LastName"=$lname;"Age"=$age}
return $OutTable

}

This prints out nicely, except it is in the wrong order.

 PS>Get-ReallySimple Joe Dokes 32

 Name                           Value
----                            -----
Age                            32
FirstName                      Joe
LastName                       Dokes

By adding the ordered keyword in front of the hash table definition, we can get the hash table to print in the order in which we asked for the function’s input paramenters.

function Get-ReallySimple($fname,$lname,$age) {

$OutTable= [ordered] @{"FirstName"=$fname;"LastName"=$lname;"Age"=$age}
return $OutTable

}

PS>Get-ReallySimple Joe Dokes 32

Name                           Value
—-                                —–
FirstName                     Joe
LastName                     Dokes
Age                               32

Since the result is a hash table we can also return a portion of the table using dot notation. We surround the functional call with parentheses to force the call to be evaluated first.

PS>(Get-ReallySimple Joe Dokes 32).FirstName

Joe

Of course instead of the the parentheses we probably should assign the call to a variable; and then dot notate that.

$Zilch=Get-ReallySimple Joe Dokes 32

$Zilch.FirstName
Joe

There is  an Output Type attribute that can be applied to a function, but this appears to be cosmetic. It doesn’t enforce or do any error checking.  If your function returns a string, and Output type says “hashtable”, nothing happens; the function still return the string.  According to the help documentation the purpose of the Output Type attribute is to provide documentation; but when I queried with Get-Command Get-ReallySimple,  it returned nothing for the output.

Advertisements

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