我使用PowerShell在多个服务器上更新应用程序的XML目录列表,但在进行实际更新时遇到问题。使用以下XML作为示例,希望使用qualnas1更新文件路径以使用类似\ GlobalNAS ...等的内容并删除qualnas2条目。
<?xml version="1.0" encoding="UTF-8" ?>
<directory>
<filepath>\\qualnas1\library\content</filepath>
<filepath>\\qualnas2\library\content</filepath>
<filepath type="sssb">\\qualnas1\SSSB\content</filepath>
</directory>
当我使用$ _。InnerText时,type = sssb的文件路径节点有效,但无法找到更新或删除其他节点的方法。这是我的代码:
$DirectoryXMLPath = 'C:\Temp\directory.xml'
if (Test-Path $DirectoryXMLPath)
{
$DirectoryXML = New-Object XML
$DirectoryXML.Load($DirectoryXMLPath)
$DirectoryXML.PreserveWhitespace = $true
# Find qualnas1 path and replace with GlobalNAS
$DirectoryXML.directory.filepath | Where-Object { $_ -eq '\\qualnas1\library\content' } |
ForEach-Object { $_.InnerText = '\\GlobalNAS\library\content' }
# Find extraneous library paths and remove them
$DirectoryXML.directory.filepath.Remove('\\qualnas2\library\content')
# $DirectoryXML.directory.mountpoint | Where-Object { $_ -eq '\\qualnas2\library\content' } |
# ForEach-Object { $DirectoryXML.RemoveChild($_) }
# This line is good! Need InnerText as attribute type exists
$DirectoryXML.directory.filepath | Where-Object { $_.InnerText -eq '\\qualnas1\SSSB\content' } |
ForEach-Object { $_.InnerText = '\\GlobalNAS\SSSB\content' }
}
如果我使用PowerGUI逐步执行代码,找到每个节点并尝试替换/删除,但是要么得到错误(字符串到XmlElement转换),要么没有错误但没有更新,这取决于如何我做任务。无论如何在SSSB示例中没有属性的情况下更改/删除特定节点?
答案 0 :(得分:5)
我会使用一点Xpath来获取XML节点的句柄。对我来说,这比使用PowerShell为XML节点创建的属性更容易。
# Find qualnas1 path and replace with GlobalNAS
$DirectoryXML.SelectNodes('/directory/filepath') | ? {
$_.InnerText -eq '\\qualnas1\library\content'
} | % {
$_.InnerText = '\\GlobalNAS\library\content'
}
# Find extraneous library paths and remove them
$DirectoryXML.SelectNodes('/directory/filepath') | ? {
$_.InnerText -eq '\\qualnas2\library\content'
} | % {
$_.ParentNode.RemoveChild($_)
}