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.
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.
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.
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.
2 thoughts on “Find and Replace Text with PowerShell”
Comments are closed.