28

I am trying to pass array of arguments to powershell script file.

I was trying to pass the commandline like this in command line.

Powershell -file "InvokeBuildscript.ps1" "z:\" "Component1","component2"

But it doesn't take the parameters it seems. What am i missing? how to pass array of arguments?

3 Answers 3

36

Short answer: More double quotes could help...

suppose the script is "test.ps1"

param(

    [Parameter(Mandatory=$False)]
    [string[]] $input_values=@()

)
$PSBoundParameters

Suppose would like to pass the array @(123,"abc","x,y,z")

Under Powershell console, to pass multiple values as an array

.\test.ps1 -input_values 123,abc,"x,y,z"

Under Windows Command Prompt Console or for Windows Task Scheduler; A double-quote are replaced by 3 double-quotes

powershell.exe -Command .\test.ps1 -input_values 123,abc,"""x,y,z"""

Hope it could help some

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

4 Comments

The trick here is to use explicit -command instead of -file.
I was able to use -input_values 123,abc,'x,y,z'
Reiterating, what Mike pointed out since I missed it also in this answer. What worked for me was calling Powershell.exe from the batch file with -command instead of -file
This doesn't help if you have no control over test.ps1.
12

try

Powershell -command "c:\pathtoscript\InvokeBuildscript.ps1" "z:\" "Component1,component2"

if test.ps1 is:

$args[0].GetType()
$args[1].gettype()

call it from a dos shell like:

C:\>powershell -noprofile -command  "c:\script\test.ps1" "z:" "a,b"

returns :

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object
True     True     Object[]                                 System.Array

Comments

1

One can also pass array variables as command line arguments. Example:

Consider the following Powershell Module

File: PrintElements.ps1

Param(
    [String[]] $Elements
)

foreach($element in $Elements)
{
   Write-Host "element: $element"
}

To use the above powershell module:

#Declare Array Variable
[String[]] $TestArray = "Element1", "Element2", "Element3"

#Call the powershell module
.\PrintElements.ps1 $TestArray

And if you want to concatenate and pass the TestArray as a single string of space separated elements then you can call the PS module by enclosing the argument in quotes as shown below:

#Declare Array Variable
[String[]] $TestArray = "Element1", "Element2", "Element3"

#Call the powershell module
.\PrintElements.ps1 "$TestArray"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.