Issue with ForEach-Object in the pipeline

104 Views Asked by At

Bonjour

This a question from a newbie... Could you tell me why this works?

$Data = Import-Csv -Path ./Data1.csv -Delimiter ';' 
$Data | ForEach-Object {
  $_.Question = $_.Question -replace "`n", "<br/>"
  $_.Response = $_.Response -replace "`n", "<br/>"
}
$Data | Export-Csv -Path "./Data1-bis.csv" -Encoding UTF8

And why this doesn't?

Import-Csv -Path ./Data1.csv -Delimiter ';' | 
ForEach-Object {
  $_.Question = $_.Question -replace "`n", "<br/>"
  $_.Response = $_.Response -replace "`n", "<br/>"
} |
Export-Csv -Path "./Data1-bis.csv" -Encoding UTF8

I've been locked on this for a while now, so your help is welcome Regards, Philippe

1

There are 1 best solutions below

0
Santiago Squarzon On

The second example doesn't work because assignments don't produce output thus Export-Csv is not receiving any input. For it to work properly you would need to output the updated object ($_):

Import-Csv -Path ./Data1.csv -Delimiter ';' | ForEach-Object {
  # update here
  $_.Question = $_.Question -replace "`n", "<br/>"
  $_.Response = $_.Response -replace "`n", "<br/>"
  # output here
  $_
} | Export-Csv -Path "./Data1-bis.csv" -Encoding UTF8