How to Replace Multiple Strings in a File using PowerShell

Replace the Data Source and Initial Catalog values of WebConfig.XML

Content of XML file

<Configuration ConfiguredType=”Property” Path=”\Package.Connections[ConnStaging].Properties[ConnectionString]” ValueType=”String”>
<ConfiguredValue>Data Source=localhost;Initial Catalog=Stage;Integrated Security=SSPI; Connection Timeout = 10</ConfiguredValue>
</Configuration>

webConfig

PARAM(
[String]$DatabaseName='DCTarget',
[String]$XML='c:\webconfig.XML',
[String]$DatabaseServer='DataCenterDB01')
[string]$db = 'Catalog='+ $DatabaseName
[string]$dbs = 'Source='+ $DatabaseServer
(Get-Content $XML) | 
Foreach-Object {
$_ -replace "Catalog=([A-Za-z0-9_]+)", $db -replace "Source=([A-Za-z0-9_]+)", $dbs } | Set-Content $XML

webConfig1

The above code can be used to modify the content of any files or even copy the modified content to new file

$Sourcefile = 'c:\filename.txt'
$desfile =  'c:\Newfilename.txt'
(Get-Content $Sourcefile) | Foreach-Object {
    $_ -replace 'Prashanth', 'Jayaram' `
       -replace 'SQL', 'PowerShell' 
    } | Set-Content $destFile

webConfig2

Advertisements

About Prashanth Jayaram

I’m a Database technologist having 11+ years of rich, hands-on experience on Database technologies. I am Microsoft Certified Professional and backed with a Degree in Master of Computer Application. My expertise lies in T-SQL programming, Replication and PowerShell You can connect me via https://social.technet.microsoft.com/profile/prashanth jayaram/ http://www.sqlshack.com/author/prashanth/ https://www.tumblr.com/blog/prashantjayaram http://www.sqlservercentral.com/blogs/powersql-by-prashanth-jayaram/ http://www.toadworld.com/members/prashanthjayaram/ My Articles are published in following sites http://www.ssas-info.com/analysis-services-articles/ http://db-pub.com/ http://www.sswug.org/sswugresearch/community/
This entry was posted in PowerShell, String handling and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s