Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 523
mishkin Avatar asked Aug 22 '11 19:08

mishkin


People also ask

Can you pass an array as a parameter?

Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.

How do you pass an array as a parameter in a function?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.

Can you pass an array as a parameter in Javascript?

We can pass the entire array to the function as an argument to simplify the code.


1 Answers

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.

like image 127
manojlds Avatar answered Oct 13 '22 21:10

manojlds