从CSV中读取列数据 [英] Read Column data from CSV
本文介绍了从CSV中读取列数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个CSV文件
Name,Age,Data
Test,22,Yes
Test2,23,No
Test3,43,Yes
PowerShell,以便我可以复制此功能:
How can I process this file using PowerShell, so that I can replicate this functionality:
foreach(var HeaderName in CSV.HeaderName)
{
//Sample value Name
foreach(var data in HeaderColumn.Data)
{
//Do Something with data
//Sample values as we loop through will be
//Test,Test2,Test3
}
}
其中 CSV.HeaderName
应该具有 Name
, Age
,数据
和 HeaderColumn.Data
将具有<$ c $在处理标题时, Age
和
Where CSV.HeaderName
should be having the values Name
, Age
, Data
and HeaderColumn.Data
will have the column data for Name
, Age
and Data
as we process the headers.
推荐答案
PowerShell等价的伪代码将是这样:
The PowerShell equivalent of your pseudo code would be something like this:
$csv = Import-Csv 'C:\path\to\your.csv'
$headers = $csv | Get-Member -MemberType NoteProperty | select -Expand Name
foreach ($header in $headers) {
foreach ($data in $csv.$header) {
# do stuff with $data
}
}
为了更好的答案,
For better answers take a step back and describe the actual problem you're trying to solve instead of what you perceive as the solution.
演示:
PS C:\> $csvfile = 'C:\temp\test.csv'
PS C:\> Get-Content $csvfile
Name,Age,Data
Test,22,Yes
Test2,23,No
Test3,43,Yes
PS C:\> $csv = Import-Csv $csvfile
PS C:\> $csv | Format-Table -AutoSize
Name Age Data
---- --- ----
Test 22 Yes
Test2 23 No
Test3 43 Yes
PS C:\> $headers = $csv | Get-Member -MemberType NoteProperty | select -Expand Name
PS C:\> $headers
Age
Data
Name
PS C:\> foreach ($header in $headers) {
>> foreach ($data in $csv.$header) {
>> Write-Host $data
>> }
>> }
>>
22
23
43
Yes
No
Yes
Test
Test2
Test3
这篇关于从CSV中读取列数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文