所以我正在写一个PowerShell脚本,它将检查文件夹中的XML文件是否有节点,如果没有,它将添加一个空字符串的节点。如果没有,它将添加一个空字符串的节点,这就是我的PowerShell脚本的样子。
$files = Get-ChildItem "L:\Notes" -Filter *.xml -Recurse | % { $_.FullName }
#add tag confirmation message
$msg = 'Do you want to add to XML file? [Y/N]'
foreach ($file in $files) {
write-host "searching " -NoNewline
write-host ($file)
write-host "`n`r"
[xml]$xml = Get-Content $file
$NodeCheck = $xml.note.from
if ($NodeCheck) {
write-host "from tag was found at"
write-host ($file)
write-host ($NodeCheck.Value)
write-host "`n`r"
[void][System.Console]::ReadKey($true)
} else {
do {
$response = Read-Host -Prompt $msg
if ($response -eq 'y') {
#test method
$xml.note.from
} elseif($response -eq 'n') {
write-host "Nothing changed"
write-host "`n`r"
} else{
write-host "invalid response"
write-host "`n`r"
}
} until ($response -eq 'n'-or $response -eq 'y')
$xml.Save($file)
}
}
所以作为一个例子,它将读取note.xml为
<note>
<to>Tove</to>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<color/>
</note>
并希望将其改为
<note>
<to>Tove</to>
<from></from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<color/>
</note>
然而,除了代码中没有添加缺失的标签外,它添加的是关闭标签,而不是保留自闭标签,所以XML看起来是这样的
<note>
<to>Tove</to>
<from></from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<color></color>
</note>
如何防止PowerShell更改自闭标签?
你也许可以稍微整理一下你的代码。我省略了收集你的文件和循环它们,因为你知道如何做。我把你最初的XML例子复制到我的桌面上,并给它起了个很有想象力的名字......
$xml = [System.Xml.XmlDocument](Get-Content .\Desktop\test.xml -Raw)
if (!$xml.SelectNodes("note/*").name.Contains("from")) {
$from = $xml.CreateNode("element","from","")
$to = $xml.SelectSingleNode("note/to")
$xml.note.InsertAfter($from,$to)
}
$xml.Save(".\Desktop\test.xml")
$xml.OuterXml
輸出
<note><to>Tove</to><from /><heading>Reminder</heading><body>Don't forget me this weekend!</body><color /></note>