簡體   English   中英

Powershell 腳本添加 XML 子元素

[英]Powershell script to add XML sub-elements

我快瘋了。 我需要在 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>

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

< 參數名稱="f" 值="OK" />

但我想在第一個 Section < Section name="x"> 中添加新行

    #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";

我找不到解決方案。 請幫我

像這樣的東西應該工作。 請注意,我的 XML 技能與 Powershell 遠非好,所以我希望其他人有更好的解決方案

# 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)

由於您有多個Section節點,因此您需要將新的子節點指定為 append 到:


$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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM