64

For some reason, it looks like I cannot pass array of strings as parameter to scriptblock. What am I doing here wrong?

My script which is called from another script:

param(
    [parameter(Mandatory=$true)]
    [string[]]$myarr
)

foreach ($elem in $myarr){
    $elem
}

I call it from another script as

 $myarr = @("111", "222")
 start-job -filepath myscript.ps1 -arg $myarr

I got only the first item in the array - "111".

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mishkin
  • 5,932
  • 8
  • 45
  • 64

1 Answers1

87

Try it like below:

start-job -filepath myscript.ps1 -arg (,$myarr)

The -ArgumentList takes in a list/array of arguments. So when you give -arg $myarr, it is as though you are passing the elements of the array as the arguments. So you have to force PowerShell to treat it as a single argument which is an array.

Yan Sklyarenko
  • 31,557
  • 24
  • 104
  • 139
manojlds
  • 290,304
  • 63
  • 469
  • 417
  • yep, it works. Can you explain why? :) as I understand it comma in () means it is actually an array with two sub arrays, right? – mishkin Aug 22 '11 at 20:20
  • 8
    @Mishkin - Explanation would be that the -ArgumentList takes in a list/ array of arguments. So when you give `-arg $myarr`, it is as though you are passing the elements of the array as the arguments. So you have to force powershell to treat it as a single argument which is an array. – manojlds Aug 22 '11 at 21:11
  • How would you pass the array and another variable? -arg (,$myarr, $singleValue). For the example, $singleValue = "x" – Taco_Buffet Jun 16 '17 at 15:27
  • 1
    The problem only happens when try to pass a single array argument, when you pass an array and another argument then you implicitly create another array with the comma. e.g in `-arg $array, $value` the `$array, $value` expression is an array which you can see by evaluating it on the command line. `($arr, 5)[0]` will print $arr; `($arr, 5)[1]` will print 5 – Tamir Daniely Apr 22 '19 at 07:52