PoshCode Logo PowerShell Code Repository

Replace-InTextFile (modification of post by view diff)
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/1707"></script>download | new post

A script to do replace strings in text files. Yes, this is just a wrapper around (gc) -replace | sc

  1. # Replace-InTextFile.ps1
  2. # Replace Strings in files
  3. param (
  4.         [string] $Path = "."
  5.       , [string] $Filter           # Select no files, by default....
  6.       , [string] $pattern = $(Read-Host "Please enter a pattern to match")
  7.       , [string] $replace = $(Read-Host "Please enter a replacement string")
  8.       , [switch] $recurse = $false
  9.       , [switch] $caseSensitive = $false
  10. )
  11.  
  12. if ($pattern -eq $null -or $pattern -eq "") { Write-Error "Please provide a search pattern!" ; return }
  13. if ($replace -eq $null -or $replace -eq "") { Write-Error "Please provide a replacement string!" ; return }
  14.  
  15. function CReplace-String( [string]$pattern, [string]$replacement )
  16. {
  17.    process { $_ -creplace $pattern, $replacement }
  18. }
  19. function IReplace-String( [string]$pattern, [string]$replacement )
  20. {
  21.    process { $_ -ireplace $pattern, $replacement }
  22. }
  23.  
  24. $files = Get-ChildItem -Path $Path -recurse:$recurse -filter:$Filter
  25.  
  26. foreach($file in $files) {
  27.    Write-Host "Processing $($file.FullName)"
  28.    if( $caseSensitive ) {
  29.       $str = Get-Content $file.FullName | CReplace-String $pattern $replace
  30.       Write-Host $str
  31.       Set-Content $file.FullName $str
  32.    } else {
  33.       $str = Get-Content $file.FullName | IReplace-String $pattern $replace
  34.       Write-Host $str
  35.       Set-Content $file.FullName $str
  36.    }
  37. }
  38.  
  39. if($files.Length -le 0) {
  40.    Write-Warning "No matching files found"
  41. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me