Thursday, 13 September 2012

Passing arrays with ArgumentList

Just working with a collection of objects, that were being passed into a remote hosted Invoke-Command.
An old curiosity of Powershell just came back and caused me a few minutes head scratching.
I then searched on Google for

  • Truncated array
  • Passing array into Invoke-Command
  • Only getting the first item in an array when passed as parameter
It was at this last item that I realised what I was doing! 

So, let's take you through it:

#A collection of objects
$privateHosts = @($serviceMap | where {$_.key -match "_private"})

Invoke-Command -session $msmq_session -ScriptBlock {
    param ([object]$privateHostApplications)
    .... code and stuff

} -ArgumentList $privateHosts

Then, the magic started... My original array of $privateHosts which contained 28 objects, turned into only 1 after it had entered the remote Invoke-Command.

The reason for this, is that the -ArgumentList is a strange parameter that accepts an "array of parameters". It was receiving my array of host entries, and treating each entry as a unique parameter value. My parameter declaration was only setup to receive one such object, and thus, i was left with only one.

The solution is simple.
Encapsulate $privateHosts in an array itself, using the ,

} -ArgumentList ,$privateHosts

Now, the first and only parameter in my Invoke-Command call, is an array of objects.

Hope this helps!