Question regarding renaming of files and content within files using Powershell following the solution here.
With the script below, all file names and occurrences within the files are renamed. The replacement is case-insensitive, i.e. no matter if there is an occurrence "uvw", "UVW", "Uvw", etc., the replacement is "XYZ". Is it possible to respect the case of the original and rename "true to original", i.e. "uvw" -> "xyz", "UVW" -> "XYZ", "Uvw" -> "Xyz" (also "abc_123" should be "def_123" and not "DEF_123" by default)?
$filePath = "C:\root_folder"
$include = '*.txt', '*.xml' # adapt as needed
Get-ChildItem -File $filePath -Recurse -Include $include |
Rename-Item -WhatIf -PassThru -NewName { $_.Name -replace 'UVW', 'XYZ' } |
ForEach-Object {
($_ | Get-Content -Raw) -replace 'ABC_123', 'DEF_123' |
Set-Content -NoNewLine -LiteralPath $_.FullName
}
So, this is incredibly inefficient but I don't see a way around it, you need to use a match evaluator and a hashtable to map the matched characters with their replacement character.
The code will look different depending on if you're on PowerShell 7+ where Replacement with a script block exists or if you're on Windows PowerShell 5.1 where you need to call the
Regex.ReplaceAPI targeting one of theMatchEvaluatoroverloads).