The other day had created two arrays with the same length and I wanted to output them as columns in a CSV file. I couldn’t find an exact cmdlet to do this so I wrote a small script. Let’s get started.
If you have two arrays such as:
$arr1 = 'a', 'b', 'c', 'd'
$arr2 = 1 , 2 , 3 , 4
I want to output the two arrays into a CSV such as each array is a column:
col1,col2
a,1
b,2
c,3
d,4
Effectively, $arr1
and $arr2
are columns for the CSV file.
ℹ️ I assume that all arrays are the same length. We can add any number of arrays for columns.
We can output the two arrays into a CSV file:
# Single line solution
$result = @("Col1,Col2"); $result += for ($i=0; $i -lt $arr1.Count; $i++) { $arr1[$i] + ", " + $arr2[$i] }; $result > output.csv
# Multi-line solution
$arr1 = 'a', 'b', 'c', 'd'
$arr2 = 1 , 2 , 3 , 4
$outputFile = '.\output.csv'
Out-File $outputFile
Add-Content $outputFile -Value 'Col1,Col2'
for ($i=0; $i -lt $arr1.Count; $i++)
{
$line = $arr1[$i] + ", " + $arr2[$i]
Add-Content $outputFile -Value $line
};
The script works by iterating through the arrays. For each value in the arrays output it in a comma seperated line.
Now we can import the CSV back into PowerShell and work with it again or use in Excel:
$myCsv = Import-Csv .\output.csv
# Output:
#
# col1 col2
# ---- ----
# a 1
# b 2
# c 3
# d 4
I hope it helps! ✌️👩💻