2

I have a large data set in a CSV file of which I'm attemting to update the records without success.

Here is what I have:

$MailData = Import-Csv $MailDB -Delimiter '|'

$update = $MailData | ForEach-Object {
  if ($_.subject -like 'GGN*') {
    $_.status = 1
    $_.status_modified = (Get-Date).ToString('yyyy-MM-dd HH-mm-ss')
  }
}

$update | Export-Csv $MailDB -Delimiter '|' -NoTypeInformation

I've also tried the -Append switch and tried to do it with Set-Content. In all cases the content of $MailData is changed, but when I re-import the CSV file the data is not updated.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Lucas Wolfe
  • 83
  • 1
  • 7

1 Answers1

1

You need to output the records at the end of the ForEach-Object loop, otherwise the result wouldn't have any data and you'd effectively truncate your file.

(Import-Csv $MailDB -Delimiter '|') | ForEach-Object {
    if ($_.subject -like 'GGN*') {
        $_.status = 1
        $_.status_modified = (Get-Date).ToString('yyyy-MM-dd HH-mm-ss')
    }
    $_
} | Export-Csv $MailDB -Delimiter '|' -NoType
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • I've been away from PowerShell for roughly four years. I completely forgot what the $_ was for. $_ is an alias for automatic variable $PSItem. You an find the answer here: https://stackoverflow.com/questions/3494115/what-does-mean-in-powershell – Code Novice Jul 17 '23 at 22:01