2

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
David
  • 68
  • 1
  • 7
  • If I understand what you are trying to do, you don't actually need to put anything in those elseif blocks. There isn't anything wrong with redirecting to null either though. – EBGreen Jan 25 '18 at 16:49
  • Yep, that works! The result is in fact the same as redirect to null. So I can just leave the blocks empty until something else needs to happen with those lines. Thanks! – David Jan 25 '18 at 16:55
  • For thess things they have the keywords Continue, Break, Return and Exit. See https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_language_keywords?view=powershell-5.1 for the full documentation. – bluuf Jan 25 '18 at 17:08

1 Answers1

5

This isn't applicable for what you're doing, but it answers your initial question:

You have four options to suppress the stdout stream (also referred to as &1, success, or output).

  1. [Void]() type-casting
  2. $Null = () assignment
  3. () > $Null redirection
  4. () | Out-Null cmdlet (note this is the slowest of the options by an order of magnitude)

This code block should address your problem:

$original = 'input.txt'
$destination = 'output.txt'
$tempfile = [IO.Path]::GetTempFileName()

Switch -Regex -File $original
{
    '^C,' { "$_,append this" | Out-File -FilePath $tempfile -Append }
    '^[JBO],' { }
    'Default' { $_ | Out-File -FilePath $tempfile -Append }
}
Copy-Item -Path $tempfile -Destination $destination
Remove-Item -Path $tempfile

Extra information on Switch:

The Default keyword specifies a condition that is evaluated
only when no other conditions match the value.

The action for each condition is independent of the actions in
other conditions. The closing brace ( } ) in the action is an
explicit break.

Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63