gpt4 book ai didi

powershell - 替换语句创建重复行

转载 作者:行者123 更新时间:2023-12-02 23:39:54 26 4
gpt4 key购买 nike

我正在使用下面的代码

$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)
}

最佳答案

简短的答案是,因为您正在复制它(当前脚本将其输出两次)。尝试以下方法:

$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
}

$_
}

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

关于powershell - 替换语句创建重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44971409/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com