PowerShell中批量修改XML节点下所有子节点值的实现方法
Absolutely! You can simplify this by iterating over all child elements of your source SMSServerConf node instead of hardcoding each property. This way, your script will automatically handle any new elements added to the XML structure, and you won't have to update it every time the schema changes.
Here's the revised PowerShell code:
# Load source and target XML files $s_xml = [xml](Get-Content $s_location) $d_xml = [xml](Get-Content $d_location) # Get references to the source and target SMSServerConf nodes $sourceConf = $s_xml.Configuration.SMSServerConf $targetConf = $d_xml.Configuration.SMSServerConf # Iterate over all child elements in the source node foreach ($childElement in $sourceConf.ChildNodes) { # Only process actual XML elements (skip whitespace/text nodes) if ($childElement.NodeType -eq [System.Xml.XmlNodeType]::Element) { # Update the target element's value with the source's value $targetConf.$($childElement.Name) = $childElement.InnerText } } # Save the updated target XML $d_xml.Save($d_location)
How this works:
- Get node references: We first grab both the source and target
SMSServerConfnodes to avoid repeating the long path each time. - Loop through child elements: Using
ChildNodes, we iterate over every node inside the source configuration. We filter for onlyElementtype nodes to skip any whitespace or comment nodes that might be present in the XML. - Dynamic assignment: For each element, we use its name (
$childElement.Name) to dynamically access the corresponding property on the target node and set its value to the source element's inner text.
This approach keeps your script maintainable—any new elements added to the XML will be automatically copied over, and you won't have to modify the script when elements are removed (they just won't be processed, leaving the target's existing values intact if you don't want to clear them).
If you ever need to also remove elements from the target that aren't present in the source, you could add an extra loop to check for those, but based on your question, the above should cover your core use case perfectly.
内容的提问来源于stack exchange,提问作者Yonnatan Bar

