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.