使用两个不同的正则表达式替换 PowerShell 中的文本

Use two different regex expressions to replace text in PowerShell

我试图通过以下脚本在每个文件中找到一张 Amex 信用卡和一张 Visa 卡,并将 PAN 的主要部分替换为星星,每端只留下 4 个。现在可以了,但是我用下面的脚本得到了一个奇怪的结果,而不是仅仅替换部分 VISA 卡号,它添加了该行的副本和替换。然后,当脚本为 Amex 混淆运行下一个 If 语句时,它会正常工作。

有谁知道我的逻辑哪里出了问题?将不胜感激。

$Enhanced_TRXReports = Get-ChildItem $TRXDestinationFilePath -include "Payment.txt","InvoiceHeader.txt" -File -Recurse

foreach ($Enhanced_TRXReport in $Enhanced_TRXReports){
$ReportPath = $Enhanced_TRXReport.FullName
$ReportName = $Enhanced_TRXReport.Name
$content = (Get-content $ReportPath) | ForEach {
    if($_ -match ",4[0-9]{15},"){
    $matched = $Matches[0]
    $String = $_
    $firsthalf = $matched.Substring(1,4)
    $secondhalf = $matched.Substring(13,4)
    $final = "," + $firsthalf + '********' + $secondhalf + ","
    [regex]$regex = ",4[0-9]{15},"
    $String -replace $regex,$final 
    }
    if($_ -match ",3[0-9]{14},"){
    $matched = $Matches[0]
    $String = $_
    $firsthalf = $matched.Substring(1,4)
    $secondhalf = $matched.Substring(12,4)
    $final = "," + $firsthalf + '*******' + $secondhalf + ","
    [regex]$regex = ",3[0-9]{14},"
    $String -replace $regex,$final 
}
    else
    {
        $_
    }
    }
Set-Content -Path $ReportPath -Value $content
}

使用纯正则表达式,这里有一种更简单的处理方法,您不会以双重处理结束(主要是因为 switch 语句是显式中断)。我假设这些行上可能有非卡号,虽然我没有这样做,但我假设这实际上是一个 CSV。另外,according to this site,amex 可以是 34 或 37,所以我已经针对这种情况进行了更新。

#Requires -Version 4

(Get-ChildItem -Path $Path -Include payment.txt,invoiceheader.txt -File -Recurse).ForEach({
    (Get-Content -Path $PSItem.FullName).ForEach({
        ($PSItem -split ',').ForEach({
            switch -Regex ($PSItem) {
                '4\d{15}' {
                    $PSItem -replace '(\d{4})\d{8}(\d{4})', '********'
                }
                '3[47]\d{13}' {
                    $PSItem -replace '(\d{4})\d{7}(\d{4})', '*******'
                }
                default {
                    $PSItem
                }
            }
        }) -join ','
    }) | Set-Content -Path $PSItem.FullName
})

所以我的脚本不工作的原因是因为对于第二个 if 语句我没有使用 else if。使用 else if 后,脚本按预期工作。 TheIncorrigible1 是正确的。