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.

function Edit-uc4ini($filespec, $search, $replace) {
<#
.DESCRIPTION
This function performs inline file editing like sed.

.PARAMETER $filespec
File to edit

.PARAMETER $search
Text to find in file

.PARAMETER $replace
Replacement text

.EXAMPLE
Edit-uc4ini "c:\uc4g5\Executor\Windows\bin\UCXJWX6.ini" "WIN01" "node" 
#>
foreach ($file in Get-ChildItem -Recurse $filespec | ? { Select-String $search $_ -Quiet } )
{
(Get-Content $file) |
ForEach-Object {$_ -replace $search, $replace } |
Set-Content $file
}
}

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.

foreach ($file in gci -Recurse $filespec | ? { Select-String $search $_ -Quiet } )
{
(gc $file) |
ForEach-Object {$_ -replace $search, $replace } |
Set-Content $file
}

Conclusion

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.

top