Reputation: 1202
I have a CSV file
Name,Age,Data
Test,22,Yes
Test2,23,No
Test3,43,Yes
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
}
}
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.
Upvotes: 1
Views: 1302
Reputation: 200503
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.
Demonstration:
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
Upvotes: 1