How to Replace String in XML File using PowerShell?

    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:

    1. We define the path to the XML file we want to modify.
    2. We load the XML file into a PowerShell variable $xmlContent.
    3. We specify the old server address that we want to replace and the new server address.
    4. We use the -replace operator to swap the old address with the new one within the DatabaseConnectionString element.
    5. We save the modified XML content back to the original file.
    6. 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:

    >