50

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?

2
  • 8
    '"' + ($myArray -join '","') + '"' Commented Sep 1, 2016 at 17:59
  • Write-Host "Comma separated string: $($arryOfStrings -join ', ')" Commented Sep 24, 2020 at 7:26

9 Answers 9

58

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 '.

Sign up to request clarification or add additional context in comments.

1 Comment

I do not recommend this method. Take a look at Powershell 7 - Array to CSV or Earler versions of Powershell - Array to CSV
48

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"

3 Comments

Super clean and works with outputted array, this is the best answer.
This is absolutely brilliant. Would you mind breaking down what is happening in the expression $b = '"{0}"' -f ($myArray -join '","') please ? Thank you very much.
$myArray -join '","' result is file1.csv","file2.csv. Then the -f operator puts this result between double-quotes
16

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"

Comments

1

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'
    

1 Comment

This is nice, but remember that if you try to join an array of numbers, like $q =@(1,2,3), you can no longer use -in test. Example: $p = @(1,2,3); $q = '{0}' -f ($p -join ','); 2 -in $p; 2 -in $q; with output: True, False.
1

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"

1 Comment

Most portable, flexible, and least cryptic solution given so far, in my opinion. Deserves to be higher than this.
0

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"

Comments

0

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"

Comments

0

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.

Comments

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

output:

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

1 Comment

Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.