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’)
Comment by EBGreen — October 8, 2008 @ 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.
Comment by santoshbenjamin — October 8, 2008 @ 9:33 pm
Aaah…I understand.
Comment by EBGreen — October 8, 2008 @ 10:45 pm