Find And Replace Values In All Files With Powershell

The aim of this page📝 is to write a short PowerShell snippet finding and replacing values in all markdown files within a folder/subfolders.

  • this is for all markdown files (*.md)
  • get a .FullName property after a folder is filtered with dir command
  • iterate over the collection with ForEach-Object loop structure
  • use -Raw for Get-Content ~> Get-Content without the parameter -Raw produces an array of strings (one string per line), this would be messy with Set-Content without newlines param (see below)
  • use -NoNewLine for Set-Content ~> version control will not be finding newlines at the end
function find_and_replace($find, $replace) {
(dir *.md -Recurse).FullName | ForEach-Object {
(Get-Content -Path $_ -Raw) -replace "$find", "$replace" |
Set-Content -Path $_ -NoNewline }
}

Technical Support Engineer of Behavioural Data Platform (Snowplow Analytics). On comparison of programming languages, history of computing, and raw playbooks.