How do I pass an array as a parameter to another script?
Asked Answered
U

1

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".

Upali answered 22/8, 2011 at 19:45 Comment(0)
K
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.

Kinghood answered 22/8, 2011 at 20:8 Comment(4)
yep, it works. Can you explain why? :) as I understand it comma in () means it is actually an array with two sub arrays, right?Upali
@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.Kinghood
How would you pass the array and another variable? -arg (,$myarr, $singleValue). For the example, $singleValue = "x"Comely
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 5Optometrist

© 2022 - 2024 — McMap. All rights reserved.