endothermic
endothermic

Reputation: 27

Why is this switch deleting an extra line (PowerShell)

This code is supposed to find a line with a regular expression and replace the line with "test". It is finding that line and replace it with "test" but also deleting the line under it, no matter what is in the next line down. I feel like I am just missing something about how a switch works in PowerShell.

Note: This is super boiled down code. There is a larger program this is part of.

$reg = '^HI\*BH'
$appendText = '' 
$file   = Get-ChildItem (join-path $PSScriptRoot "a.txt.BAK")

foreach ($f in $file){

  switch -regex -file $f {

    $reg
    {
     
     $appendText = "test"
     
    }
    default {

      If ($appendText -eq '') {$appendText = $_}
      $appendText
      $appendText = ''
    }
  }
  
}

a.txt.BAK

HI*BH>00>D8>0*BH>00>D8>0*BH>A1>D8>0*BH>B1>D8>0000000~
HI*BE>02>>>0.00*BE>00>>>0.00~
NM1*71*1*TTT*NAME****XX*0000000~
PRV*AT*PXC*000V00000X~

Output:

test
NM1*71*1*TTT*NAME****XX*0000000~
PRV*AT*PXC*000V00000X~

Upvotes: 0

Views: 51

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174690

The switch is not "deleting" anything - but you explicit ask it to overwrite $appendText on match, and you only ever output (and reset the value of) $appendText when it doesn't.

This code is supposed to find a line with a regular expression and replace the line with "test".

In that case I suggest you simplify your switch:

switch -regex -file $f {
    $reg {
        "test"
    }
    default {
        $_
    }
}

That's it - no fiddling around with variables - just output "test" on match, otherwise output the line as-is.


If you insist on using the intermediate variable, you'll need to output + reset the value in both cases:

switch -regex -file $f {
    $reg {
        $appendText = "test"
        $appendText
        $appendText = ''
    }
    default {
        $appendText = $_
        $appendText
        $appendText = ''
    }
}

Upvotes: 1

Related Questions