UPDATE: Went with the marked preferred solution based on other project needs. I also modified it slightly to throw out any column provided that isn't in the source, again, due to some other project needs.
$refTable = @'
SourceColumn,TargetColumn
LastName,Last_Name
DOB,Date_Of_Birth
FirstName,First_Name
'@ | ConvertFrom-Csv
$source = @'
FirstName,DOB,NotInRefCol,LastName
Tom,06/07/1940,1,Jones
Bill,11/27/1955,2,Nye
William,04/01/1564,3,Shakespeare
'@ | ConvertFrom-Csv
$map = @{}
foreach($line in $refTable) {
$map[$line.SourceColumn] = $line.TargetColumn
}
foreach($line in $source) {
$out = [ordered]@{}
foreach($prop in $line.PSObject.Properties) {
if (!($refTable.SourceColumn.Contains($prop.Name))) {
continue
}
if($newCol = $map[$prop.Name]) {
$out[$newCol] = $prop.Value
continue
}
$out[$prop.Name] = $prop.Value
}
[pscustomobject]$out
}
I have a set of data in CSV format, and I'm trying to output the same data with different headers based on column names in a mapping document. The column names below are just an example for clarity, but the names can be drastically different, and the order may not match the order of the columns in the mapping file. I haven't done much Powershell work lately, so I'm having a tough time getting started. I can't seem to figure out the logic for looking up column names based on the data I'm looking at. For instance, if I do a foreach ($row in $source) how would I know how to order the columns? Any assistance would be appreciated!
Examples:
map.csv
SourceColumn,TargetColumn
LastName,Last_Name
DOB,Date_Of_Birth
FirstName,First_Name
source.csv
FirstName,LastName,DOB
Tom,Jones,06/07/1940
Bill,Nye,11/27/1955
William,Shakespeare,04/01/1564
Desired output:
output.csv
Last_Name,Date_Of_Birth,First_Name
Jones,06/07/1940,Tom
Nye,11/27/1955,Bill
Shakespeare,04/01/1564,William