Santosh Benjamin's Weblog

Adventures with AppFabric, BizTalk & Clouds

Powershell and Arrays as named parameters

with 5 comments


While theres a ton of stuff on the usage of Powershell as an interactive scripting system there is not as much from a general programming perspective of a developer , at least not much that i could find today.

For example, while there is a flood of posts showing how you can manipulate the “args” system variable and how you can pass in an array on the command line by simply putting in several arguments with spaces, i was looking for a way to pass parameters into a function where 1 of the several parameters happened to be an array and then i needed to parse that array. After much trial and error, i found a solution. Here it is for any powershell newbies to benefit.

My main script file has a function like this  (very trivialised example)

function showfriends([string] $mainPerson, [string[]] $friends)
{
 Write-Host “Main person is “,$mainPerso
 Write-Host ‘friends count is : ‘ ,$friends.Count
 foreach($friend in $friends)
 {
  Write-Host $mainPerson “has a friend named:” ,$friend
  }

}

Now to call it i use the following line

showfriends -mainPerson:Smith  -friends:@(‘Jon’, ‘Joshua’)

which will then print

Smith has a friend namd Jon

Smith has a friend named Joshua

The reason i got stuck intiially was that i was trying to use foreach-object and PS insisted on prompting me to enter the objects. Another thing that got me stuck was that on a site with tutorials , the illustration of some syntax had showed the usage of [array]  which did not work for me.

Advertisement

Written by santoshbenjamin

September 30, 2008 at 7:07 PM

Posted in General, Powershell

Tagged with

5 Responses

Subscribe to comments with RSS.

  1. You can call it like this if you want as well:

    showfriends Smith (‘Jon’, `Joshua’)

    EBGreen

    October 8, 2008 at 8:43 PM

  2. Thanks. I’ll bear that in mind for the next time. The key problem for me this time was how to get the values out of that parameter and i was messing with different foreach-xyz things.

    santoshbenjamin

    October 8, 2008 at 9:33 PM

  3. Aaah…I understand.

    EBGreen

    October 8, 2008 at 10:45 PM

  4. […] Neat trick, and you can also pass arrays in as a script parameter too.  Found this: https://santoshbenjamin.wordpress.com/2008/09/30/powershell-and-arrays-as-named-parameters/ […]


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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: