简体   繁体   中英

Powershell is removing comma from program argument

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?

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

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

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"

如果您从批处理文件传递参数,则将您的参数括起来,如下所示“”“Param1,Param2,Param3,Param4”“”

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]

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