Replace String in Multiple Files in PowerShell

💡 TL;DR

To replace String in multiple files, use Get-ChildItem to get all the required files and iterate over the files using ForEach-Object. In each iteration, read the file content using Get-Content cmdlet, use replace() method to replace text and Set-Content to save the content in the files.
Here is simple example:

Let’s say, you want to replace all the spaces to underscore in all txt files under folder C:\Users\Arpit\Desktop\powershell.

Replace String in multiple Files in PowerShell

There are 2 different ways to replace String in multiple Files in PowerShell.

Using replace() method with Get-ChildItem

Here are the steps to replace String in multiple files using replace() method.

  • Store the file path in variable $DirPath
  • Use Get-ChildItem cmdlet to get all the required files in $DirPath . You can use -include option to select only particular file extension.
  • Use ForEach-Object to iterate over each item.
  • In each iteration, use Get-Content cmdlet to read content of the file. Get-Content reads the content of the item at particular location specified by the path.
  • Use replace() method to replace old text with new text. replace() method returns new String and replaces each occurence of old text with new text.
  • Lastly, use Set-Content cmdlet to replace the content of the all the files.

Using replace operator with Get-ChildItem

Most of the steps will be similar to previous method. We will use replace operator instread of replace() method to replace content in multiple files.

Here are the steps to replace String in multiple files using replace operator.

  • Store the file path in variable $DirPath
  • Use Get-ChildItem cmdlet to get all the required files in $DirPath. You can use -include option to select only particular file extension.
  • Use ForEach-Object to iterate over each item.
  • In each iteration, use Get-Content cmdlet to read content of the file. Get-Content reads the content of the item at particular location specified by the path.
  • Use replace operator to replace old text with new text. replace operator returns new String and replaces each occurence of old text with new text.
  • Lastly, use Set-Content cmdlet to replace the content of the all the files.

That’s all about how to replace String in multiple files in PowerShell.

Was this post helpful?

Leave a Reply

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