Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update the value for a XML node using PowerShell?

Tags:

powershell

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)
like image 524
SRA Avatar asked Jul 08 '10 10:07

SRA


People also ask

How do I replace a string in a PowerShell file?

Finding and Replacing the String One way to do that is to use the -replace operator. This PowerShell operator finds a string and replaces it with another. Using the example file contents, we can provide the search string foo with the replacement string bar which should make the file contents foo foo baz now.

How run XML file in PowerShell?

One way to read an XML document in PowerShell is to typecast a variable to the type [xml]. To create this variable, we can use the Get-Content cmdlet to read all of the text in an XML document. To typecast the output of Get-Content we can simply prepend the text [xml] before the variable.

How do I edit a text file in PowerShell?

Method 1: Using Notepad The easiest way to edit a text file in PowerShell on your Windows machine is to run the command notepad.exe my_text_file. txt , or simply notepad my_text_file. txt , in your PowerShell terminal to open the text file with the visual editor Notepad.


1 Answers

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.

like image 146
stej Avatar answered Oct 13 '22 19:10

stej