Powershell is removing comma from program argument

Viewed 16644

I want to pass in a comma separated list of values into a script as part of a single switch.

Here is the program.

param(
  [string]$foo
)

Write-Host "[$foo]"

Here is the usage example

PS> .\inputTest.ps1 -foo one,two,three

I would expect the output of this program to be [one,two,three] but instead it is returning [one two three]. This is a problem because I want to use the commas to deliminate the values.

Why is powershell removing the commas, and what do I need to change in order to preserve them?

5 Answers

Powershell with remove the commas and use them to deliminate an array. You can join the array elements back into a string and put a comma between each one.

param(
  [string[]]$foo
)
$foo_joined = $foo -join ","
write-host "[$foo_joined]" 

Any spaces between your arguments will be removed, so this:

PS> .\inputTest.ps1 -foo one, two, three

will also output: [one,two,three]

If you need the spaces you'll need quotes, so do this:

PS> .\inputTest.ps1 -foo one,"two is a pair"," three"

if you want to output: [one,two is a pair, three]

Related