Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell is removing comma from program argument

Tags:

powershell

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?

like image 347
StaticMethod Avatar asked Aug 16 '12 15:08

StaticMethod


People also ask

How do you use commas in PowerShell?

Commas are array separators in PowerShell. You should either escape them or encase the parameter in double quotes and then write some logic to split your string that contains commas. E.g. Your cmdlet call should be: Get-Weather "Shrewsbury,MA?

What does @() mean in PowerShell?

What is @() in PowerShell Script? In PowerShell, the array subexpression operator “@()” is used to create an array. To do that, the array sub-expression operator takes the statements within the parentheses and produces the array of objects depending upon the statements specified in it.

What is Param block in PowerShell?

The PowerShell parameter is a fundamental component of any script. A parameter is a way that developers enable script users to provide input at runtime. If a PowerShell script's behavior needs to change in some way, a parameter provides an opportunity to do so without changing the underlying code.

What does argument mean in PowerShell?

An argument is an expression used when calling the method. But for the purpose of differentiating param and args , you can consider the former as defining parameters that can be either passed to the script (or function etc.)


2 Answers

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
like image 142
John Weldon Avatar answered Oct 23 '22 06:10

John Weldon


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

like image 20
marekzbrzozowa Avatar answered Oct 23 '22 05:10

marekzbrzozowa