Updating XML Files Using PowerShell

I use PowerShell to update the list of XML directories for an application on multiple servers, but this causes a problem with the actual updates. Using the following XML as an example, you want to update file paths with qualnas1 to use something like \ GlobalNAS ... etc. And delete the qualnas2 entry.

<?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> 

The path to the node file with type = sssb works when I use $ _. InnerText, but cannot find a way to update or delete other nodes. Here is my code:

 $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' } } 

If I go through the code using PowerGUI, each node will be found, and the replace / remove attempt will be performed as I expected, but either get errors (XmlElement conversion string) or no errors, but no updates, either depending of how I complete the task. In any case, to change / delete certain nodes if there are no attributes, as in the SSSB example?

+6
source share
1 answer

I would use a little Xpath to get the XML node descriptor. This is easier for me than using the properties that PowerShell creates for XML nodes.

 # 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($_) } 
+5
source

Source: https://habr.com/ru/post/908183/


All Articles