PowerShell: Find and Replace in Files

Here’s a PowerShell function that does a recursive Find and (optional) Replace in all files within a parent directory.

Function FindReplaceInFiles
{
  param(
    [string]$ParentPath,
    [string]$Find, 
    [string]$Replace,
    [string[]]$Exclude
  )
 
  $Files = Get-ChildItem  -Path $ParentPath\*.* -Recurse -Exclude $Exclude
  ForEach ($File in $Files) {    
    $Content = Get-Content -Path $File.FullName
    If ($Content | Select-String -Pattern $Find) { 
      If ($Replace -ne "") {
        Write-Host Replacing in $File.FullName
        $Content | ForEach { $_ -replace $Find, $Replace } | Set-Content -Path $File.FullName
      } Else {
        Write-Host Found in $File.FullName
      }
    }
  }
}
 
FindReplaceInFiles -ParentPath "C:\my\path\to\somewhere" -Find "something" -Replace "something_else" -Exclude "*.exe", "*.config"

There are a number of other switches for Select-String, such as “CaseSensitive” and “SimpleMatch”, so you could easily pass those switches through to the function to get more fine grained find/replace functionality. Don’t forget, if you do switch to case sensitive matches, that the “-replace” would also need to be replaced with “-creplace”.

Hope this helps!

This entry was posted in PowerShell. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *