【问题标题】:Powershell Array to comma separated string with QuotesPowershell数组以逗号分隔的字符串与引号
【发布时间】:2017-01-09 15:03:57
【问题描述】:

我有一个数组,我需要输出到逗号分隔的字符串,但我还需要引号“”。这是我所拥有的。

$myArray = "file1.csv","file2.csv"
$a = ($myArray -join ",")
$a

输出为 $a 结束了

file1.csv,file2.csv

我想要的输出是

"file1.csv","file2.csv"

我怎样才能做到这一点?

【问题讨论】:

  • '"' + ($myArray -join '","') + '"'
  • Write-Host "逗号分隔字符串:$($arryOfStrings -join ', ')"

标签: arrays string powershell join


【解决方案1】:

给你:

[array]$myArray = '"file1.csv"','"file2.csv"'
[string]$a = $null

$a = $myArray -join ","

$a

输出:

"file1.csv","file2.csv"

你只需要想办法逃离"。所以,你可以通过'来做到这一点。

【讨论】:

    【解决方案2】:

    我知道这个帖子很旧,但这里有其他解决方案

    $myArray = "file1.csv","file2.csv"
    
    # Solution with single quote
    $a = "'$($myArray -join "','")'"
    $a
    # Result = 'file1.csv','file2.csv'
    
    # Solution with double quotes
    $b = '"{0}"' -f ($myArray -join '","')
    $b
    # Result = "file1.csv","file2.csv"
    

    【讨论】:

    • 超级干净并与输出数组一起使用,这是最好的答案。
    • 这真是太棒了。你介意分解一下表达式 $b = '"{0}"' -f ($myArray -join '","') 中发生的事情吗?非常感谢。
    • $myArray -join '","' 结果为file1.csv","file2.csv。然后-f 运算符将此结果放在双引号之间
    【解决方案3】:

    如果使用 PowerShell Core(当前为 7.1),您可以使用 Join-String
    这在 PowerShell 5.1 中不可用

    $myArray | Join-String -DoubleQuote -Separator ','
    

    输出:

    "file1.csv","file2.csv"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      相关资源
      最近更新 更多