search
top

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

Introduction

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.

Conclusion

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

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.

top