【问题标题】:Powershell script to add XML sub-elements用于添加 XML 子元素的 Powershell 脚本
【发布时间】:2021-02-26 11:30:16
【问题描述】:

我快疯了。我需要在 powershell 中修改这个 XML 文件

<Smart>
  <Settings>
    <Section name="x">
      <Parameter name="a" value="true" />
      <Parameter name="b" value="0" />
      <Parameter name="c" value="13873" />
      <Parameter name="d" value="true" />
      <Parameter name="e" value="EAI" />
    </Section>
    <Section name="z">
      <Parameter name="h" value="true" />
      <Parameter name="i" value="0" />
      <Parameter name="j" value="13873" />
      <Parameter name="k" value="true" />
      <Parameter name="l" value="EAI" />
    </Section>
  </Settings>
</Smart>

我想要做的是添加另一行,例如:

但我想在第一个 Section

中添加新行
    #Modify XML file
    Write-Host "OPENING XML FILE";
    $path = "\\$computer\$FileName"
    [xml] $xml = Get-Content $path
    
    #return $xml.SmartUpdate.Settings.Section.Parameter

    #set values for the XML nodes you need. This uses the XPath of the value needed.

   **WANT TO ADD THE NEW PARAMETER HERE**

    #Save the file
    $xml.save($path)
    Write-Host "XML FILE SAVED";

我找不到解决方案。请帮帮我

【问题讨论】:

  • 您可以使用 msxsl 和 XSLT 样式表

标签: xml powershell


【解决方案1】:

由于您有多个Section 节点,您需要指定将新子节点附加到的节点:


$path = "\\$computer\$FileName"
[xml]$xml = Get-Content -Path $path -Raw

# create a new childnode and append attributes to it
$childNode = $xml.CreateElement("Parameter")
$attrib = $xml.CreateAttribute('name')
$attrib.Value = 'f'
[void]$childNode.Attributes.Append($attrib)
$attrib = $xml.CreateAttribute('value')
$attrib.Value = 'OK'
[void]$childNode.Attributes.Append($attrib)

# select the parent node to append this childnode to
$parentNode = $xml.Smart.Settings.Section | Where-Object { $_.name -eq 'x' }
[void]$parentNode.AppendChild($childNode)

$xml.Save($path)

【讨论】:

    【解决方案2】:

    这样的事情应该可以工作。 请注意,我使用 Powershell 的 XML 技能远非好,所以我希望其他人有更好的解决方案

    # Create a new node
    $NewNode = $Xml.CreateNode([System.Xml.XmlNodeType]::Element,"Parameter",$null)
    # create the attributes and set the values
    $NameAttribute = $XMl.CreateAttribute('name')
    $NameAttribute.Value = 'f'
    $ValueAttribute = $Xml.CreateAttribute('value')
    $ValueAttribute.Value = 'OK'
    # append the attributes
    $NewNode.Attributes.Append($NameAttribute)
    $NewNode.Attributes.Append($ValueAttribute)
    # append the new node to the correct parent
    $Xml.Smart.Settings.Section.AppendChild($NewNode)
    

    【讨论】:

    • 嗨,谢谢。有效。如果设置中有两个部分,我该怎么办?
    最近更新 更多