Eric
Eric

Reputation: 941

Powershell Array to comma separated string with Quotes

I have an array that I need to output to a comma separated string but I also need quotes "". Here is what I have.

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

The output for $a ends up

file1.csv,file2.csv

My desired output is

"file1.csv","file2.csv"

How can I accomplish this?

Upvotes: 50

Views: 148237

Answers (9)

Agitech
Agitech

Reputation: 51

$array = @(0,1,2,3,4,5)
"@($('"' + ($array -join '","') + '"'))"

output:

@("0","1","2","3","4","5")

Upvotes: 0

zett42
zett42

Reputation: 27756

I had the requirement to double-quote only strings that contain whitespace.

$myArray = 'foo', 'b ar', "ba`tz" 
$myArray -replace '.*\s.*', '"$0"' -join ','

Output:

foo,"b ar","ba  z"

This takes advantage of the fact that the RegEx-based -replace operator can take an array as the LHS operand. In this case it outputs a new array with any replacements done.

The RegEx pattern .*\s.* matches any string that contains at least one whitespace character. The .* match any surrounding characters, so the whole input string will be matched, if it contains a whitespace. The replacement pattern "$0" then quotes the whole match. If there is no match, the input string will be passed on without quoting.

Finally, -join joins the quoted strings.

Upvotes: 0

js2010
js2010

Reputation: 27428

Here's another one, using the builtin foreach method, and escaping doublequotes with backquotes:

$myarray = echo file1.csv file2.csv
$myarray.ForEach{"`"$_`""} -join ','

"file1.csv","file2.csv"

Upvotes: 1

woter324
woter324

Reputation: 3080

Just a slight addition to @Jason S's answer, adding a carriage return (and line feed - a Windows thing):

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

And with the comma:

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

Upvotes: 0

One-line solutions

Supposing there is an array or list inside $myArray. Defined such as:

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

We have two solutions:

  1. Using double-quotes ( " ) as separator:

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

    Outputs:

    "one","two"
    
  2. Using single-quotes ( ' ) as separator:

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

    Outputs:

    'one','two'
    

Upvotes: 1

Derek Sanderson
Derek Sanderson

Reputation: 1

Here's a Join-String method that will work in older methods of 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
    }
}

It can be invoked with array parameter or passthrough

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

Output:

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

or as pass-thru:

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

Output:

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

Without -DoubleQuote

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

Output:

file1.txt,file2.txt,file3.txt

or with a custom separator, say a semicolon

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

Output:

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

Upvotes: 0

Jason S
Jason S

Reputation: 1544

If using PowerShell Core (currently 7.1), you can use Join-String
This is not available in PowerShell 5.1

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

Output:

"file1.csv","file2.csv"

Upvotes: 16

abillon
abillon

Reputation: 629

I know this thread is old but here are other solutions

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

Upvotes: 48

Syphirint
Syphirint

Reputation: 1121

Here you go:

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

$a = $myArray -join ","

$a

Output:

"file1.csv","file2.csv"

You just have to get a way to escape the ". So, you can do it by putting around it '.

Upvotes: 57

Related Questions