Skip to content
Menu
The Lonely Administrator
  • PowerShell Tips & Tricks
  • Books & Training
  • Essential PowerShell Learning Resources
  • Privacy Policy
  • About Me
The Lonely Administrator

Find and Replace Text with PowerShell

Posted on February 27, 2014

magnifying-glass I've just finished up a series of tweets with a follower who had a question about finding and replacing a bit of data in a text file. In his case it was a web.config file but it really could be any text file that you can view in PowerShell. In PowerShell 3.0 and later this isn't too difficult. Although I haven't tested with really large files to determine if there are any limitations. Before you try anything I'm going to show you, please have a backup copy of of the original file.

Manage and Report Active Directory, Exchange and Microsoft 365 with
ManageEngine ADManager Plus - Download Free Trial

Exclusive offer on ADManager Plus for US and UK regions. Claim now!

Let's say I have a file like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    
  <configSections>
   <section
        name="ADVWRK"
type="System.Configuration.NameValueSectionHandler,system, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null" />
  </configSections>
  <ADVWRK>
     <add key="ConnectionString" value='data source=192.168.97.199;initial catalog=Adventure_Works_Cycle_MSCRM;password="";persist security info=True;user id=sa;workstation id=CRMSERVER;packet size=4096' />
     <add key="TraceMode" value="0" />
     <add key="UserName" value="" />
     <add key="Password" value="" />
     <add key="Domain" value="" />
     <add key="CRMServer" value="CRM.Company.com" />
  </ADVWRK>
  <system.web>
 <customErrors mode="Off"/>
<compilation defaultLanguage="C#" debug="false"/>
<identity impersonate="true"/>
<pages buffer="true" enableSessionState="false" enableViewState="true"/>
 </system.web>
</configuration>

I need to change the IP source address in the connection string. As you probably guessed Get-Content is going to come into play. Normally when you use Get-Content you get an array of strings which adds a little complexity. But starting in v3 Get-Content has a -Raw parameter which writes the entire file as a single string. If we have a single string then we can easily use -Replace.

$find = "192.168.97.199"
$replace = "192.168.97.200"
$content = Get-Content $file -Raw
#write replaced content back to the file
$content -replace $find,$replace | Out-File $file 

Your replacement pattern could even be a regular expression pattern. This could even be done as a one-liner:

(get-content $file -raw) -replace $find,$replace | out-file $file

For many of you, especially with unstructured text files, this technique should get the job done. But in this case, because the text file is also an XML document we could tackle the problem a different way. This is especially useful if you have several changes you want to make to the file.

First, create an XML document from the file.

[xml]$config = get-content $file

We can navigate the document until we find the entry we need to change.

xmlconfig

We can assign a new value with revised connection string:

$newcs = 'data source=192.168.97.200;initial catalog=Adventure_Works_Cycle_MSCRM;password="";persist security info=True;user id=sa;workstation id=CRMSERVER;packet size=2048'

$config.configuration.ADVWRK.add[0].value = $newcs

All that remains is to save the file back to disk.

#save the XML to file
$config.Save($file)

Or, if you didn't necessarily know the structure of your document, you could use an XPath query with Select-XML to find the node and then change the value.

$cs =  $config | Select-Xml -XPath '//*[@key="ConnectionString"]'

#assign the value
$cs.node.value = $newcs

#save the XML to file
$config.Save($file)

The node properties will vary depending on your XML file so you will need to look at the object.
xmlnode

The XML approach is a bit more involved but is predictable and you don't have to save the file until you have the XML just the way you want it.

One thing I will say about both techniques is that the more you understand how to use regular expressions in PowerShell the more you can accomplish. If you are feeling a little wobbly on the topic, there is an entire chapter on regular expressions in PowerShell in Depth.


Behind the PowerShell Pipeline

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on Mastodon (Opens in new window) Mastodon
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Pocket (Opens in new window) Pocket
  • Click to share on Reddit (Opens in new window) Reddit
  • Click to print (Opens in new window) Print
  • Click to email a link to a friend (Opens in new window) Email

Like this:

Like Loading...

Related

2 thoughts on “Find and Replace Text with PowerShell”

  1. Pingback: Find and Replace Text with PowerShell | Sergio'...
  2. Pingback: Zajímavé novinky ze svÄ›ta IT z 9. týdne 2014 | Igorovo

Comments are closed.

reports

Powered by Buttondown.

Join me on Mastodon

The PowerShell Practice Primer
Learn PowerShell in a Month of Lunches Fourth edition


Get More PowerShell Books

Other Online Content

github



PluralSightAuthor

Active Directory ADSI Automation Backup Books CIM CLI conferences console Friday Fun FridayFun Function functions Get-WMIObject GitHub hashtable HTML Hyper-V Iron Scripter ISE Measure-Object module modules MrRoboto new-object objects Out-Gridview Pipeline PowerShell PowerShell ISE Profile prompt Registry Regular Expressions remoting SAPIEN ScriptBlock Scripting Techmentor Training VBScript WMI WPF Write-Host xml

©2025 The Lonely Administrator | Powered by SuperbThemes!
%d