Powershell数组,以逗号分隔的字符串(带引号)

c0vxltue  于 2023-02-04  发布在  Shell
关注(0)|答案(6)|浏览(213)

我有一个数组,我需要输出到一个逗号分隔的字符串,但我也需要引号“"。

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

$a的输出结果为

file1.csv,file2.csv

我想要的输出是

"file1.csv","file2.csv"

我怎样才能做到这一点?

piztneat

piztneat1#

给你:

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

$a = $myArray -join ","

$a

输出:

"file1.csv","file2.csv"

你只需要找到一种方法来逃避"。所以,你可以通过把它放在'周围来做到这一点。

kse8i1jr

kse8i1jr2#

我知道这条线是旧的,但这里有其他的解决方案

$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"
tuwxkamq

tuwxkamq3#

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

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

输出:

"file1.csv","file2.csv"
irlmq6kh

irlmq6kh4#

下面是一个Join-String方法,可以在PowerShell的旧方法中使用

function Join-String {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [string[]]$StringArray, 
        $Separator=",",
        [switch]$DoubleQuote=$false
    )
    BEGIN{
        $joinArray = [System.Collections.ArrayList]@()
    }
    PROCESS {
        foreach ($astring in $StringArray) {
            $joinArray.Add($astring) | Out-Null
        }
    }
    END {
        $Object = [PSCustomObject]@{}
        $count = 0;
        foreach ($aString in $joinArray) {
            
            $name = "ieo_$($count)"
            $Object | Add-Member -MemberType NoteProperty -Name $name -Value $aString;
            $count = $count + 1;
        }
        $ObjectCsv = $Object | ConvertTo-Csv -NoTypeInformation -Delimiter $separator
        $result = $ObjectCsv[1]
        if (-not $DoubleQuote) {
            $result = $result.Replace('","',",").TrimStart('"').TrimEnd('"')
        }
        return $result
    }
}

可以使用数组参数或passthrough调用它

Join-String @("file1.txt","file2.txt","file3.txt") -DoubleQuote

输出:

"file1.txt","file2.txt","file3.txt"

或作为直通:

@("file1.txt","file2.txt","file3.txt") | Join-String -DoubleQuote

输出:

"file1.txt","file2.txt","file3.txt"

不带-双引号

@("file1.txt","file2.txt","file3.txt") | Join-String

输出:

file1.txt,file2.txt,file3.txt

或使用自定义分隔符,如分号

@("file1.txt","file2.txt","file3.txt") | Join-String -DoubleQuote -Separator ";"

输出:

"file1.txt";"file2.txt";"file3.txt"
klh5stk1

klh5stk15#

* 单线 * 解决方案

假设$myArray中有一个 * array * 或 * list *,定义如下:

$myArray = @("one", "two")

我们有两种解决方案:
1.使用**双引号(")**作为分隔符:

'"{0}"' -f ($myArray -join '","')

输出:

"one","two"

1.使用**单引号(')**作为分隔符:

"'{0}'" -f ($myArray -join "','")

输出:

'one','two'
vatpfxk5

vatpfxk56#

只是对@Jason S的答案做了一点小小的补充,增加了一个回车符(和换行符--Windows的一个东西):

$myArray | Join-String -DoubleQuote -Separator `r`n

加上逗号:

$myArray | Join-String -DoubleQuote -Separator ",`r`n"

相关问题