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

1 Answer 1

88

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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 - 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.
How would you pass the array and another variable? -arg (,$myarr, $singleValue). For the example, $singleValue = "x"
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
Also true for invoke-command -argumentlist

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.