20

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?

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
StaticMethod
  • 593
  • 1
  • 7
  • 20

5 Answers5

35

The comma is a special symbol in powershell to denote an array separator.

Just put the arguments in quotes:

inputTest.ps1 -foo "one, two, three"

Alternatively you can 'quote' the comma:

inputTest.ps1 -foo one`,two`,three
John Weldon
  • 39,849
  • 11
  • 94
  • 127
13

Following choices are available

  1. Quotes around all arguments (')

    inputTest.ps1 -foo 'one,two,three'

  2. Powershell's escape character before each comma (grave-accent (`))

    inputTest.ps1 -foo one`,two`,three

Double quotes around arguments don't change anything !
Single quotes eliminate expanding.
Escape character (grave-accent) eliminates expanding of next character

marekzbrzozowa
  • 382
  • 1
  • 3
  • 11
  • 2
    Double quotes seem to have a weird behaviour. If I use them directly in Powershell, they work, but if I launch Powershell with arguments from another program, they do not work. – NovaLogic Jun 07 '18 at 14:18
3

Enclose it in quotes so it interprets it as one variable, not a comma-separated list of three:

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

David M
  • 71,481
  • 13
  • 158
  • 186
3

if you are passing parameters from a batch file, then enclse your params as below """Param1,Param2,Param3,Param4"""

Manikanta
  • 31
  • 1
1

Powershell will remove the commas and use them to delimitate 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]

Yash Gupta
  • 1,807
  • 15
  • 21
Berven
  • 21
  • 4