Tobi123
Tobi123

Reputation: 548

Powershell & XML: Save data to a certain node of xml-file

I have a powershell script which loads data from an xml. The XML looks like:

<meta>
<log>
    <path>D:\logs\l1.log</path>
    <lastwrite>01/30/2015 13:01:00</lastwrite>
    <num>23</num>
</log>
<log>
    <path>D:\log\l2.log</path>
    <lastwrite>02/30/2015 14:02:00</lastwrite>
    <num>67</num>
</log>
</meta>

What I would like to do is to change a certain value in the xml. First I load the Data:

[xml]$xml = Get-Content "D:\config.xml"

My problem is, how can I address a certain log-Node in my xml? What I'm searching for is something like this:

$xml.meta.log.path | where path = "D:\log\l2.log"

And also something to set the new value and save it back to the xml-file.

Maybe sb can help me, I have now idea how to search, but I'm sure there's a way. To use IDs within the log-tags is not a good solution, because I have to address the nodes by the paths.

Upvotes: 1

Views: 319

Answers (2)

Tobi123
Tobi123

Reputation: 548

Ok, I made a little change: XML is now:

<meta>
<log path="D:\logs\l1.log">
    <lastwrite>01/30/2015 13:01:00</lastwrite>
    <num>23</num>
</log>
<log path="D:\log\l2.log">
    <lastwrite>02/30/2015 14:02:00</lastwrite>
    <num>67</num>
</log>
</meta>

And now this code works:

$configPath = 'D:\config.xml'

[xml]$xml = Get-Content $configPath

# Select the log log node where path equals 'D:\log\l2.log' 
$node = $xml.meta.log | where {$_.path -eq 'D:\log\l2.log'}

# Set the new path
$node.line_num = "5"

# Save the xml back
$xml.Save($configPath)

Path is not needed to be modified.

Thanks for your help. Wouldn't have been able to solve this without your code snippet;)

Upvotes: 1

Martin Brandl
Martin Brandl

Reputation: 58931

You are almost there. Instead of a = use the -eq condition. You also have to use curly brackets and access the current value using $_:

$xml.meta.log.Path | where { $_ -eq 'D:\log\l2.log' }

Alternative, you can use the where path query on $xml.meta.log and select the path in an additional statement:

$xml.meta.log | where path -eq 'D:\log\l2.log' | select -expand path

And here a complete example which modifies the path and save the xml back:

$configPath = 'D:\config.xml'

[xml]$xml = Get-Content $configPath

# Select the log log node where path equals 'D:\log\l2.log' 
$node = $xml.meta.log | where path -eq 'D:\log\l2.log' 

# Set the new path
$node.path = 'D:\newLogPath\newLog.log'

# Save the xml back
$xml.Save($configPath)

Upvotes: 1

Related Questions