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)
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With