Wednesday 20 February 2013

Passing an array to invoke-command

When passing an array to invoke-command to be used on a remove machine, the PARAM will only read the first entry if passed as below:

$ar = @("a","b","c")
invoke-command -ArgumentList $ar -ComputerName mypc1 -ScriptBlock {param($opts);write-host $opts;write-host $opts.length}


Result:
a
1

To read in the array correctly, use the syntax (,$myArray)

$ar = @("a","b","c")
invoke-command -ArgumentList (,$ar) -ComputerName mypc1 -ScriptBlock {param($opts);write-host $opts;write-host $opts.count}


Result:
a b c
3