I have a CSV -
title,client,tech,name,version,createdby,created
sampleTitle,MyCompany,Office365,sampleMonday,11.0,Luke Wilkins,2020-05-08T19:10:08Z
I'd like to enumerate through that CSV and use both the header and the value. Is there a way without specifying $variable.title, $variable.client etc
cheers
You have some options depending on how you want to use them. I'm going to expand your example to help all of us.
Create the sample file
$tempfile = New-TemporaryFile
@'
title,client,tech,name,version,createdby,created
sampleTitle1,MyCompany1,Office365,sampleMonday,11.0,Luke Wilkins,2020-05-08T19:10:08Z
sampleTitle2,MyCompany2,Office365,sampleMonday,12.0,Luke Wilkins,2020-05-08T19:10:08Z
'@ | Out-File $tempfile -Encoding utf8
Import the CSV
$csvdata = Import-Csv $tempfile
To simply get each header/value this is one way.
$csvdata | foreach {
$_.psobject.properties | foreach {
"Name: {0}`nValue: {1}" -f $_.name,$_.value
}
}
Which shows (trimmed)
Name: title
Value: sampleTitle1
Name: client
Value: MyCompany1
Name: tech
Value: Office365
Name: name
Value: sampleMonday
Name: version
Value: 11.0
Name: createdby
Value: Luke Wilkins
Name: created
Value: 2020-05-08T19:10:08Z
Something I frequently do is create custom objects with the headers as the properties.
$csvdata | foreach {
$ht = [ordered]@{}
$_.psobject.properties | foreach {$ht += @{$_.name = $_.value}}
[pscustomobject]$ht
} -OutVariable hashtable
Which shows and stores the following output
title : sampleTitle1
client : MyCompany1
tech : Office365
name : sampleMonday
version : 11.0
createdby : Luke Wilkins
created : 2020-05-08T19:10:08Z
title : sampleTitle2
client : MyCompany2
tech : Office365
name : sampleMonday
version : 12.0
createdby : Luke Wilkins
created : 2020-05-08T19:10:08Z
And if you need to create a property list out of the column headers you can use
$props = $csvdata | select -First 1 | foreach {$_.psobject.properties.name}
or
$props = (Get-Content $tempfile -TotalCount 1).split(',')
And we can use the properties to access the data in the hashtable variable like this.
$props | foreach {$hashtable.$_}
Or by using the property index
1..3 | foreach {$hashtable.($props[$_])}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments