Question

I am trying to pass an array to a PowerShell script, but I always get just one value. I have googled my butt off, but I can't find anything. All I need to do is pass an array to the script. Here is my code:

param($Location)
($location).count

Foreach ($loc in $Location)
{

$loc

}

Here is my command I am running:

C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe -ExecutionPolicy Unrestricted  -File "C:\ParaTestingArray.ps1" -location Sydney,London

Here is the output:

1
Sydney

For the life of me I can't get it to grab the other value in the array. I have tried using

param([string[]]$Location)

I have tried:

-location "Sydney","London"
-location @(Sydney,London)
-location Sydney London
-location Sydney,London
-location (Sydney,London)

What am I doing wrong?

Was it helpful?

Solution 2

I cannot reproduce that result:

$script = @'
param($Location)
($location).count

Foreach ($loc in $Location)
{

$loc

}
'@

$script | sc test.ps1

.\test.ps1 sydney,london

2 sydney london

Edit: This works:

$args.count

Foreach ($loc in $args)
{

$loc

}

Called as: powershell.exe -file c:\test.ps1 sydney london

OTHER TIPS

Use the -command switch instead.

Like this:

powershell -Command "&{C:\ParaTestingArray.ps1 -Location A,B,C}"

From the about_powershell:

For writing a string that runs a Windows PowerShell command, use the format:

     "& {<command>}"

Where the quotation marks indicate a string and the invoke operator (&) causes the command to be executed.

The

Powershell.exe -Command "&{C:\script.ps1 -ParmArray 1,2,3}"

trick worked for me - but it feels unfortunately hacky. Definitely counter-intuitive after the rest of my powershell experience.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top