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

99,375

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.

Share:
99,375
mishkin
Author by

mishkin

Updated on January 21, 2020

Comments

  • mishkin
    mishkin over 4 years

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

  • mishkin
    mishkin over 12 years
    yep, it works. Can you explain why? :) as I understand it comma in () means it is actually an array with two sub arrays, right?
  • manojlds
    manojlds over 12 years
    @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.
  • Taco_Buffet
    Taco_Buffet almost 7 years
    How would you pass the array and another variable? -arg (,$myarr, $singleValue). For the example, $singleValue = "x"
  • Tamir Daniely
    Tamir Daniely about 5 years
    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