Using A PowerShell Function To Search and Replace in a Text file


When I started working in PowerShell for scripting in Windows I longed for a way to do inline editing of a file like you could do with sed. I was able to do this with VBScript but it was long and ugly. After learning more about some of the cmdlets I was able to create a function to search and replace. In this post I would like to share the simple function with you.

The Code

The overall code is very small for this PowerShell script and relies on Get-ChildItem, Select-String, Get-Content, Set-Content and runs in a ForEach-Object loop. I developed the function to edit a configuration file for a scheduling program called UC4 and named itĀ Edit-uc4ini and it is run taking three command line input variablesĀ $filespec, $search and $replace. Which are File to edit, what to replace and what to replace with. Here is the code with the help verbiage.

The core code is really simple. We use Get-ChildItem to open the file and Select-String to find what we want to change and then run a loop and replace and write the changes.


Hope this is useful to you as it is to me. The function is not much but it is reusable in many instances.

One Response to “Using A PowerShell Function To Search and Replace in a Text file”

  1. Kamarul says:

    I have 150 PC with host name and specific computer description.

    How do I use PS to read from the file and change it accordingly

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.