简体   繁体   中英

Passing an array to a PowerShell script

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?

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM