I am having a little trouble creating/populating a csv file with powershell. I am new to powershell, so I may be missing some obvious things, so please go easy on me. Here is the situation:
First I am creating an array(?) to act as my table
#Create output table with headers
$output = @()
$row = New-Object System.Object
$row | Add-Member -MemberType NoteProperty -Name "Example Header 1" -Value $null
$row | Add-Member -MemberType NoteProperty -Name "Example Header 2" -Value $null
$row | Add-Member -MemberType NoteProperty -Name "Example Header 3" -Value $null
$output += $row
I am writing it to a file using
$output | Export-Csv new.csv -NoTypeInformation
This appears to make a csv file with the headers that I want. If there is a better way to do this, please let me know. The next step is where I am running into problems. I now need to programatically populate the table with data. When importing existing csv files, I am able to access/modify data in the table like an array (i.e. $output[rowIndex]."Header Name" = "new data"
).
So I tried to add data to my newly created table. I wrote $ouput[0]."Example Header 1" = "Test Data"
. This works as I expected and populates the first row in the column with the specified header with "Test Data". However, I can ONLY access [0]. $output[1]
and so on cause errors because I guess they do not exist. I tried using $output += $row
again to add more rows, but it does not work at all and causes some strange errors to happen (if I write to a row, it writes to all rows, probably because its all the same object).
So basically my question is, how can I create a csv file from scratch, add some headers to it, and then start writing to all the (unknown/variable number of) rows? I am sure there is a better way to do it, but like I said, I am very new to powershell. Ideally I would like to be able to access rows by index (0,1,2, etc) but I am open to whatever.
Basic solution (adapted from Martin Brandl's answer)
This basically reads data from one csv file, and inserts it into another with new specified headers.
$csv = Import-Csv "MyCsv.csv"
$newCsv = @()
foreach($row in $csv) {
$newCsv += [PSCustomObject]@{
"New Column Header1" = $row."Original Column Header1"
"New Column Header2" = $row."Original Column Header2"
}
}