我有一个powershell脚本,可以从xml加载数据。 XML看起来像:
<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>
我想要做的是更改xml中的某个值。首先我加载数据:
[xml]$xml = Get-Content "D:\config.xml"
我的问题是,如何在我的xml中寻址某个日志节点?我正在寻找的是这样的:
$xml.meta.log.path | where path = "D:\log\l2.log"
还可以设置新值并将其保存回xml文件。
也许sb可以帮助我,我现在已经知道如何搜索,但我确信这是一种方式。在日志标记中使用ID不是一个好的解决方案,因为我必须通过路径来寻址节点。
答案 0 :(得分:1)
你快到了。而不是=
使用-eq
条件。您还必须使用大括号并使用$_
访问当前值:
$xml.meta.log.Path | where { $_ -eq 'D:\log\l2.log' }
或者,您可以在where path
上使用$xml.meta.log
查询,并在附加语句中选择路径:
$xml.meta.log | where path -eq 'D:\log\l2.log' | select -expand path
这里有一个完整的例子,它修改了路径并保存了xml:
$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)
答案 1 :(得分:1)
好的,我做了一点改变: XML现在是:
<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>
现在这段代码有效:
$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)
不需要修改路径。
感谢您的帮助。如果没有你的代码片段,我们就无法解决这个问题;)