14

How can I change the value of the node <Test>Test</Test> to <Test>Power</Test>?

Example:

<?xml version="1.0"?>
<configuration>
    <appSettings>
        <add key="DeploymentDate" value="test" />
        <add key="DateOfInitialization" value="Vinoj" />
    </appSettings>
    <Test>Test</Test>
</configuration>

Here's the PowerShell script I currently use:

$configuration = "app.config"
[xml]$xml = New-Object XML
$xml.Load($configuration)
$xml.selectnodes("/configuration/Test") = {"UST"}
$xml.Save($configuration)
1
  • There's a box above the question title saying "This question already has answers here..." but it links to a question that was posed in 2013. This one was asked in 2010 and already had answers that year as you can see. So... that box should be removed Commented Jul 12, 2023 at 17:51

1 Answer 1

36

I don't know what exactly you want to achieve, but the example should give you and idea:

$file = 'c:\temp\aa\ServerService.exe.config'
$x = [xml] (Get-Content $file)
Select-Xml -xml $x  -XPath //root/level |
    % { $_.Node.'#text' = 'test'
        $_.Node.SomeAttribute = 'value'
      }
$x.Save($file)

You don't need to use .NET for xpath queries. Just stay with PowerShell (with Select-Xml).
It is also common to load xml file via Get-Content and cast it to [xml] which creates XmlDocument and loads the file content.

Sign up to request clarification or add additional context in comments.

4 Comments

Worked like a charm. Can you please tell me what | % does in general?
It means foreach-object. You can find it with Get-Alias -Name %
you can also access the test value $xml.configuration.test - Pretty slick (given its not a collection) but then you can use foreach ($thing in $xml.things) { $thing.value } . I am here cause I need to save my XML file after incrementing version. And this helped me. +1
also, you asked about the pipe |. That gets the output from the previous command and feeds it into the next command, which in this case is a where-object loop using what was found from Select-Xml -xml $x -XPath //root/level. So every object passes through, but the % helps filter what you're looking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.