How to Replace Text in Files with PowerShell

Code is developed on: Windows 10 Version 1703, Build 10.0.15063.138

In this short article I will show you how to replace a matched string in multiple files. In this use case I will search for Windows Media Player playlists on \\fileserver1\media\audio. Because we are implementing DFS Namespaces, the links inside the playlists needs to be changed to \\runas\dfs\media\audio.



  • Line 1: Collects the file information in the variable $wpls
  • Line 2: We start a foreach loop here. For every file object we execute the next action:
  • Line 3: For the file object we grab the contents, search for the string ‘fileserver1’ and replace this with ‘runas\dfs’. This will only change the values in the object. After we pipe this to Out-File to write it back to the original file.

Leave a Reply

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