jeudi 25 janvier 2018

Is redirecting to null the proper way to discard a line in a PowerShell script?

I'm in the process of integrating two pieces of software that talk to each other via CSV files, but the output file from App A requires a bit of post-processing before App B can pick it up.

The code below appends data to lines beginning with "C," while discarding the other three possibilities for now, as those parts will be added at a later date.

$_ > null is something I came up with because I couldn't find a code snippet that would remove a line within a IF statement. It seems to work, but I want to be sure if it's correct.? TIA

$original = "input.txt"
$destination = "output.txt"
$tempfile = [IO.Path]::GetTempFileName()
get-content $original | foreach-object {
  if ($_ -match "^C,") {
    $_ + ",append this" >> $tempfile
  }
  elseif ($_ -match "^J,") {
    $_ > null
  }
  elseif ($_ -match "^B,") {
    $_ > null
  }
  elseif ($_ -match "^O,") {
    $_ > null
  }
  else {
    $_ >> $tempfile
  }
}
copy-item $tempfile $destination
remove-item $tempfile

Aucun commentaire:

Enregistrer un commentaire