There will be times when, as a developer, you may need to replace a string value in an XML file using PowerShell. In this PowerShell tutorial, I will show a complete example of how to replace a string in an XML file using PowerShell.
PowerShell Replace String in XML File
Let us try to understand this with a simple but complete example.
Consider the following XML file named config.xml
, which contains some configuration settings for an application:
<Configuration>
<Settings>
<DatabaseConnectionString>Server=myServerAddress;Database=myDataBase;</DatabaseConnectionString>
<FeatureFlag>Enabled</FeatureFlag>
</Settings>
</Configuration>
We want to replace the database server address myServerAddress
with newServerAddress
.
We can do this easily using PowerShell.
Here’s a complete PowerShell script that will load the XML file, replace the string, and save the changes back to the XML file:
# Define the path to the XML file
$xmlFilePath = 'C:\config.xml'
# Load the XML file content into a variable
[xml]$xmlContent = Get-Content $xmlFilePath
# Define the old and new server addresses
$oldServerAddress = 'myServerAddress'
$newServerAddress = 'newServerAddress'
# Replace the old server address with the new one
$xmlContent.Configuration.Settings.DatabaseConnectionString = $xmlContent.Configuration.Settings.DatabaseConnectionString -replace $oldServerAddress, $newServerAddress
# Save the updated XML content to the same file
$xmlContent.Save($xmlFilePath)
Write-Host "The server address in the XML file has been updated."
Here is the complete explanation:
- We define the path to the XML file we want to modify.
- We load the XML file into a PowerShell variable
$xmlContent
. - We specify the old server address that we want to replace and the new server address.
- We use the
-replace
operator to swap the old address with the new one within theDatabaseConnectionString
element. - We save the modified XML content back to the original file.
- We output a confirmation message to the console.
After running this script, the config.xml
file would be updated to look like this:
<Configuration>
<Settings>
<DatabaseConnectionString>Server=newServerAddress;Database=myDataBase;</DatabaseConnectionString>
<FeatureFlag>Enabled</FeatureFlag>
</Settings>
</Configuration>
Conclusion
This simple example demonstrates how to use PowerShell to replace a string in an XML file.
You may also like:
- PowerShell Replace String Before Character
- PowerShell Replace String Case Insensitive
- How to Replace a String in Text File with PowerShell?
I am Bijay a Microsoft MVP (10 times – My MVP Profile) in SharePoint and have more than 17 years of expertise in SharePoint Online Office 365, SharePoint subscription edition, and SharePoint 2019/2016/2013. Currently working in my own venture TSInfo Technologies a SharePoint development, consulting, and training company. I also run the popular SharePoint website EnjoySharePoint.com