Table of Contents [hide]
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.
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
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-Member
cmdlet 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.
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.
Using the Set-Content
cmdlet
For this method to work, you need to create an array like this:
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.
That’s all about how to write an array to csv in PowerShell. If you have any confusion, let us know in the comments.