A exported field might be called "Employee Number".
IMPORT-CSV creates an object with a NoteProperty called "Employee Name"
Now
$obj."Employee Name" is not valid
$obj.EmployeeName would work nicely
Is there a way to modify NoteProperty -name after IMPORT-CSV
or
Is there a way to make IMPORT-CSV remove spaces from names?
Thanks
# ceate some objects with NoteProperties with spaces in their names
# and export them to a CSV file without type information
1..3 | ForEach-Object {New-Object PSObject -Property @{
'Prop Num 1' = 'Val 1'
'Prop Num 2' = 'Val 2'
'Prop Num 3' = 'Val 3'
}
} | Export-Csv C:\Test.csv -NoTypeInformation
# quoted property name is valid
foreach ($i in Import-Csv C:\Test.csv) {
$i.'Prop Num 2'
}
# collect objects
$col0 = Import-Csv C:\Test.csv
# quoted property name on an element is valid
$col0[1].'Prop Num 1'
# - - - - - - - - - - - - - #
# build the scriptblock's content
$sbText = Import-Csv C:\Test.csv |
# filter NoteProperty with space(s)
Get-Member '* *' -MemberType NoteProperty | ForEach-Object {
# virtual Add-Member command to create the AliasProperty
"Add-Member AliasProperty {0} '{1}' -InputObject `$_" `
-f ($_.Name -replace ' '), $_.Name
}
# append a PassThru switch to last virtual Ad-Member command
$sbText[-1] += ' -PassThru'
# join the virtual commands
$sbText = $sbText -join [Environment]::NewLine
# create a ScriptBlock with the virtual commands
$sb = $ExecutionContext.InvokeCommand.NewScriptBlock($sbText)
# collect the objects with the AliasProperties
$col1 = Import-Csv C:\Test.csv | ForEach-Object $sb
# retrieve NoteProperty value through its Alias
$col1[0].PropNum3
foreach ($i in Import-Csv C:\Test.csv | ForEach-Object $sb) {
$i.PropNum1
}
# - - - - - - - - - - - - - #
# to remove/replace spaces in the CSV header
# separate header from data
$header, $data = ${C:\Test.csv}
# remove spaces
$header = $header -replace ' '
# or replace spaces
# $header = $header -replace ' ', '_'
# then set content back
${C:\Test.csv} = $header, $data
foreach ($i in Import-Csv C:\Test.csv) {
$i.PropNum2
}
$col2 = Import-Csv C:\Test.csv
$col2[1].PropNum1