I am using PowerShell to replace some strings in many files. I am trying to replace RMDB with 123 and RMDBP with 678 but using -simple match is producing something like 1236. I need to find a way to match an exact string like RMDB.
Edit -- below is the code being used
This is what I'm using right now:
$FileCount = $FILEReplaceList.Count;
$FileReplaceReport = "$ProcessedPathFileReplaceReport.csv"
#endregion
Try
{
if (Test-Path $FileReplaceReport)
{
#get the filename only
Remove-Item -Path $FileReplaceReport
}
#create the headers for the final report
Add-Content -Path $FileReplaceReport -Value '"FileName","Find","Replace","# Replaced","Total All Words Replaced"'
foreach($FILEReplace in $FILEReplaceList)
{
#Progress Bar
Write-Progress -Activity "Updating file file $($FILEReplace)" -Status "File $CurrentFile of $($FILEReplaceList.Count)" -PercentComplete (($CurrentFile++ / $FILEReplaceList.Count) * 100)
#get the Text from the file
[string] $txtFILEReplace = Get-Content $FILEReplace | Out-String
$FILEReplace
#get the file extension
$FileExtension = [System.IO.Path]::GetExtension($FILEReplace )
# Loop through all the words to be replaced
foreach ($item in $InputFile)
{
$item.FindString
# write-host "marker 1"
$iNPUTFILTERFILEEXTENSION = $item.FileExtension
$iNPUTFILTERFILEEXTENSION = $iNPUTFILTERFILEEXTENSION.Trim()
# write-host "marker 2"
#$iNPUTFILTERFILEEXTENSION = $iNPUTFILTERFILEEXTENSION.Replace('n','')
#write-host "xx"$iNPUTFILTERFILEEXTENSION"xx"
#write-host "xx"$FileExtension"xx"
# write-host "---------------------------"
# if ($item.FileExtension -eq $FileExtension)
# {
# write-host "true"
# exit
# }
#if item file extension matches file file extension then replace
if (($iNPUTFILTERFILEEXTENSION -eq $FileExtension) -or($iNPUTFILTERFILEEXTENSION -eq "all"))
{
# $item
$count = get-content $FILEReplace | select-string -Pattern "$($item.FindString)" -SimpleMatch
$NumReplaced = $count.length
$totalReplaced += $NumReplaced
Write-Host "Total Replaced $totalReplaced"
# Write-Host "Total Replaced $totalReplaced"
Add-Content -Path $FileReplaceReport -Value "$FILEReplace,$($item.FindString),$($item.ReplaceString),$NumReplaced, $totalReplaced "
$txtFILEReplace = $txtFILEReplace -replace [regex]::escape($item.FindString), "$($item.ReplaceString)"
}
}
$txtFILEReplace | Set-Content -Encoding utf8 ($FILEReplace)
}
exit
# Write-Progress -Activity "File Replace Complete" -Completed
}
Catch
{
Write-Warning $_.Exception.Message
Continue
}
$stopwatch
question from:
https://stackoverflow.com/questions/65836769/getting-an-exact-match-with-powershell-using-simplematch 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…