如何使用Powershell获取CSV数据的列标题? [英] how to get the column headers for CSV data with Powershell?

查看:75
本文介绍了如何使用Powershell获取CSV数据的列标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取CSV数据的列标题?

How can I get the column headers for CSV 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> 

我尝试过:

$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.

我已经看到了适用于原始CSV的解决方案,而此处的上下文是:

I've seen solutions which work with the raw CSV, whereas the context here being:

说明

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.

另请参阅:

使用PowerShell通过CSV从对象关系映射?

如何将已下载的CSV数据从Invoke-RestMethod传输到Import-CSV?

推荐答案

下面的一些伪代码旨在向您展示如何逐条记录地从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..}
   }

这篇关于如何使用Powershell获取CSV数据的列标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆