Powershell and Arrays as named parameters
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.
You can call it like this if you want as well:
showfriends Smith (‘Jon’, `Joshua’)
EBGreen
October 8, 2008 at 8:43 PM
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
Me and this article, sitting in a tree, L–RA–EN-I-N-G!
Reignbeau
January 13, 2015 at 2:46 PM
Aaah…I understand.
EBGreen
October 8, 2008 at 10:45 PM
[…] 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/ […]
#Powershell and Get-ExchangeServer – flaphead.com
March 19, 2014 at 12:03 AM