How can I get the column headers for CSV data?
Here is the specific data:
PS /home/nicholas/powershell/covid>
PS /home/nicholas/powershell/covid> $labsURL='http://www.bccdc.ca/Health-Info-Site/Documents/BCCDC_COVID19_Dashboard_Lab_Information.csv'
PS /home/nicholas/powershell/covid>
PS /home/nicholas/powershell/covid> $labs_csv=Invoke-RestMethod -Method Get -Uri $labsURL -Headers @{"Content-Type" = "text/csv"}
PS /home/nicholas/powershell/covid>
PS /home/nicholas/powershell/covid> $labs = $labs_csv | ConvertFrom-Csv | Format-Table
PS /home/nicholas/powershell/covid>
I've tried:
$Csv.PSObject.Properties
$csv | Get-Member
neither of which seem to give particularly useful information. Ideally, the result would be an array or list for iteration.
I've seen solutions which work with the raw CSV, whereas the context here being:
DESCRIPTION
The `ConvertFrom-Csv` cmdlet creates objects from CSV variable-length strings that are generated by the `ConvertTo-Csv`
cmdlet.
You can use the parameters of this cmdlet to specify the column header row, which determines the property names of the resulting objects, to specify the item delimiter, or to direct this cmdlet to use the list separator for the current culture as the delimiter. The objects that `ConvertFrom-Csv` creates are CSV versions of the original objects. The property values of the CSV objects are string versions of the property values of the original objects. The CSV versions of the objects do not have any methods. You can also use the `Export-Csv` and `Import-Csv` cmdlets to convert objects to CSV strings in a file (and back). These cmdlets are the same as the `ConvertTo-Csv` and `ConvertFrom-Csv` cmdlets, except that they save the CSV strings in a file.
see also:
Object Relational Mapping from CSV with PowerShell?
How to pipe downloaded CSV data from Invoke-RestMethod to Import-CSV?
The following snatch of pseudo code is intended to show you how to pick up both the names and the values from a csv file, on a record by record basis. The outer loop iterates through the records, while the inner loop iterates through the columns in the current record.
You can adapt this to suit your needs.
Import-Csv yourfile.csv | % {
$_.psobject.properties | % {Set-variable -name $_.name -value $_.value}
{do stuff with local variables here..}
}