简体   繁体   中英

Edit xml file's DefaultValue using powershell script

I want to edit the DefaultValue for the Property name = "UseThis" using PowerShell script.

Xml file:

<?xml version="1.0"?>
<ConfigFile xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" IsOverride="false">
  <Section Name="ClientConfiguration" Type="Repository.Config.Configuration">
    <Property Name="Base">
      <DefaultValue>https://app.net:190</DefaultValue>
    </Property>
    <Property Name="Subject">
      <DefaultValue>Box</DefaultValue>
    </Property>
    <Property Name="ApiVersion">
      <DefaultValue>2017-06-15</DefaultValue>
    </Property>
    <Property Name="UseThis">
      <DefaultValue>false</DefaultValue>
    </Property>
    <Property Name="Configuration">
      <DefaultValue>ServiceConfiguration</DefaultValue>
    </Property>
  </Section>
 <Section Name="ClientConfiguration1" Type="Repository.Config.Configuration1">
    <Property Name="Base">
      <DefaultValue>https://app.net:1900</DefaultValue>
    </Property>
    <Property Name="Subject">
      <DefaultValue>Box</DefaultValue>
    </Property>
    <Property Name="ApiVersion">
      <DefaultValue>2011-08-15</DefaultValue>
    </Property>
    <Property Name="UseThis">
      <DefaultValue>false</DefaultValue>
    </Property>
    <Property Name="Configuration">
      <DefaultValue>ServiceConfiguration</DefaultValue>
    </Property>
  </Section>
</ConfigFile>


   
$path = "filepath"
$xml = New-Object xml
$xml.Load($path)

$nodes =  $xml.SelectNodes("/Section/Property")
foreach($Property in $nodes)
{
    switch($Property.name)
    {
        "UseThis" 
        {
            $property.DefaultValue.Value ="True"
            $configuration.save('filepath')
        }
    }
}

The above script is not working as no value is printed for the $nodes. I am very new to powershell and any help would be very helpful. Thanks!

It looks like simple coding errors. "/ConfigFile" was missing, and ".Value" shouldn't be there. $configuration should be $xml. It's good to have the full path for these .net methods. They get confused about the current directory.

$path = "file.xml"
$xml = New-Object xml
$xml.Load("$pwd\$path")

$nodes =  $xml.SelectNodes("/ConfigFile/Section/Property")
foreach($Property in $nodes)
{
    switch($Property.name)
    {
        "UseThis" 
        {
            $property.DefaultValue ="True"
            $xml.save("$pwd\$path")
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM