You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Get node references: We first grab both the source and target SMSServerConf nodes to avoid repeating the long path each time.
  2. Loop through child elements: Using ChildNodes, we iterate over every node inside the source configuration. We filter for only Element type nodes to skip any whitespace or comment nodes that might be present in the XML.
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:33:12