简体   繁体   English

Powershell 正在从程序参数中删除逗号

[英]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] .我希望这个程序的 output 是[one,two,three]但它返回的是 [one,two, [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?为什么 powershell 删除逗号,我需要更改什么才能保留它们?

The comma is a special symbol in powershell to denote an array separator. 逗号是powershell中的一个特殊符号,表示数组分隔符。

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 (`)) 每个逗号之前的Powershell的转义字符(重音符号(`))

    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" PS>。\\ inputTest.ps1 -foo“一,二,三”

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

Powershell with remove the commas and use them to deliminate an array. Powershell 删除逗号并使用它们来分隔数组。 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: arguments 之间的任何空格都将被删除,因此:

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

will also output: [one,two,three]还将 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]如果要 output: [one,two is a pair, three]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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