Question:
I have the following Powershell script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
$oldCode = @" "@ $newCode = @" "@ ls *.html | foreach { $fileContent = [System.Io.File]::ReadAllText($_.FullName) $newFileContent = $fileContent.Replace($oldCode, $newCode) [System.Io.File]::WriteAllText($_.FullName, $newFileContent) Write-Host "`r`n" Write-Host "Processed - $($_.Name)...`r`n" } |
This doesn’t seem to be replacing the text. Is it an issue with the multiline strings, or the limits of the Replace() method? I would prefer to do the replace without bringing in regex.
Answer:
What version of PowerShell are you using? If you’re using v3 or higher, try this:
1 2 3 4 5 6 7 8 |
ls *.html | foreach { $fileContent = Get-Content $_.FullName -Raw $newFileContent = $fileContent -replace $oldCode, $newCode Set-Content -Path $_.FullName -Value $newFileContent Write-Host "`r`n" Write-Host "Processed - $($_.Name)...`r`n" } |