Powershell Array to comma separated string with Quotes
90,951
Solution 1
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 '
.
Solution 2
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"
Solution 3
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"
Author by
Eric
Updated on May 05, 2021Comments
-
Eric about 3 years
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 upfile1.csv,file2.csv
My desired output is
"file1.csv","file2.csv"
How can I accomplish this?
-
geek_01 over 5 yearsSuper clean and works with outputted array, this is the best answer.
-
Bluz over 4 yearsThis is absolutely brilliant. Would you mind breaking down what is happening in the expression $b = '"{0}"' -f ($myArray -join '","') please ? Thank you very much.
-
abillon over 4 years
$myArray -join '","'
result isfile1.csv","file2.csv
. Then the-f
operator puts this result between double-quotes -
dank8 about 2 yearsI do not recommend this method. Take a look at Powershell 7 - Array to CSV or Earler versions of Powershell - Array to CSV