替换语句创建重复行

时间:2017-07-07 12:58:53

标签: powershell

我正在使用以下代码

$content | ForEach-Object { 

$addresseeName = $_.Substring(11,50)            
$example = 'X' * 50                             
if ($_.Substring(0,10) -eq 'ADDRESSEE0')        
{ 
    $_ -replace $addresseeName, $example        

} 
else 
{ 
  $_ 
} 


$addresseeName2 = $_.Substring(62,50)           
$example = 'Y' * 50                             
if ($_.Substring(0,10) -eq 'ADDRESSEE0')        
{ 
    $_ -replace $addresseeName2, $example       
} 
else 
{ 
  $_ 
}

之前的文本文件:

ABSINVEST2|Y|N|                                                                                                                                 
ADDRESSEE0|Name Name Letters Letters & Financial             |                                                  |19 Greemount House            |
ADDRSDETAS|                                                  |                                                  |                              

文本文件后:

ABSINVEST2|Y|N|                                                                                                                                 
ADDRESSEE0|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|                                                  |19 Greemount House            
ADDRESSEE0|Samp less Independent Examples & Exampless s      |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|19 Greemount House            
ADDRSDETAS|                                                  |                                                  |                              

我试图屏蔽特定的字段(位置)。任何人都可以帮我解释为什么每条IF Else声明都重复这一行?

更新我工作的代码:

$content | 
  ForEach-Object { 

  $addresseeName = $_.Substring(11,50)
  $addresseeName2 = $_.Substring(62,50)
  $example = 'X' * 50
    if ($_.Substring(0,10) -eq 'ADDRESSEE0')    


    { 
        $_.replace($addresseeName, $example).replace($addresseeName2, $example)
    } 

1 个答案:

答案 0 :(得分:2)

简短的回答是,因为你正在复制它(你当前的脚本输出两次)。试试这个:

$content | ForEach-Object { 
    $addresseeName = $_.Substring(11,50)            
    $example = 'X' * 50                             

    if ($_.Substring(0,10) -eq 'ADDRESSEE0')        
    { 
        $_ = $_ -replace $addresseeName, $example        

    } 

    $addresseeName2 = $_.Substring(62,50)           
    $example = 'Y' * 50                             

    if ($_.Substring(0,10) -eq 'ADDRESSEE0')        
    { 
        $_ = $_ -replace $addresseeName2, $example       
    } 

    $_ 
}

这会通过在执行替换时设置它来修改当前行变量$_,然后仅在结束时输出一次(无论它是否已更改)。