I need to run a trim method on each value extracted from the csv import object. haven't tried something like below but for me I don't want to have to define a trim command at the end of each one of my variables being passed to functions.
$csvobj = "c:\somestuff.csv"
foreach ($csvitem in $csvobj) {
$csvitem.value1.trim()
$csvitem.value2.trim()
}
Thanks in advance, SS
This will trim all values in the csv file and assign the result to $csv.
$csv = Import-Csv c:\somestuff.csv | Foreach-Object {
$_.PSObject.Properties | Foreach-Object {$_.Value = $_.Value.Trim()}
}
You can try this :
$a = import-csv "c:\somestuff.csv"
$a | % {$b=$_;$_.psobject.Properties | % {$c=$_.name ;$b."$c"=($b."$c").trim()}}
First : I import all the lines into $a
.
Second : In a first loop I read each object (each CSV line), then for each object in a second loop I read each property, then I can trim each var.
Here's a slight modification of the above accepted answer. This strips all leading / tailing spaces from all .csv files in the current folder. Hope it helps!
gci -filter *.csv | foreach {
echo $_.NAME
$csv = Import-Csv $_.NAME
$csv | Foreach-Object {
$_.PSObject.Properties | Foreach-Object { $_.Value = $_.Value.Trim() }
}
$csv | Export-Csv $_.NAME -NoTypeInformation
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With