Write Array to CSV in PowerShell

This article will explain how to write an array to a CSV file in PowerShell.

Using the Export-Csv cmdlet

The Export-Csv cmdlet in PowerShell creates a CSV file of the given objects. But you cannot directly write an array to a CSV file correctly.

When you pipe the array to Export-Csv, the result will be similar to this.

Write Array to CSV file in PowerShell

The best way of exporting an array to a CSV file is to:

  • Create a PSObject from an array
  • Store PSObject in a new array
  • Pipe a new array to the Export-Csv cmdlet
$array = @('Chris', '24', 'Police'),
          ('Tom', '27', 'Farmer'),
          ('Anthony', '29', 'Lawyer')
$newarr = @()
$columns = @('Name','Age','Job')
foreach ($item in $array){
    $obj = New-Object PSObject
    for ($i=0;$i -lt $array.Length; $i++){
        $obj | Add-Member -MemberType NoteProperty -Name $columns[$i] -Value $item[$i]
    }
    $newarr+=$obj
    $obj=$null
}
$newarr | Export-Csv output.csv -NoTypeInformation

In the above example, we have created the $array to write to a CSV file. The $newarr is an empty array which will be later used to store the PSObject. The $columns contain the heading label for the data.

We created the PSObject $obj using the New-Object cmdlet. Then in for loop, we used Add-Member to add $columns values in the Name property and $array values in the Value property of the PSObject.

The New-Object cmdlet is used to create an instance of a .NET Framework or COM object.

Add-Membercmdlet is used to add custom properties to the PowerShell objects.

After that, we filled $newarr with added data in $obj.

The $newarr contains the following data now.

Name    Age Job   
----    --- ---   
Chris   24  Police
Tom     27  Farmer
Anthony 29  Lawyer

At last, we piped an array $newarr to the Export-Csv cmdlet and created a CSV file output.csv in the current directory.

The -NoTypeInformation is used to remove the #TYPE information header in a CSV file.

The array is successfully exported to a CSV file.

Write array to CSV in PowerShell

Using the Set-Content cmdlet

For this method to work, you need to create an array like this:

$array = @('Name,Age,Job'),
          ('Chris,24,Police'),
          ('Tom,27,Farmer'),
          ('Anthony,29,Lawyer')

If we use a comma to separate the multiple items, we can write it to a CSV file in the correct format.

To export this array to a CSV, you can use the Set-Content or Add-Content cmdlet.

$array | Set-Content output.csv

That’s all about how to write an array to csv in PowerShell. If you have any confusion, let us know in the comments.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.