Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editing XML with powershell

Tags:

powershell

xml

OK, I'm feeling like a really big idiot here. I've been working with Powershell for a little while more for administrative purposes at work. That said, scripting is not my strong suit.

Right now, I'm trying to write a PS script to add a section to an XML on a bunch of machines to add settings to workaround an issue we've been having with a certain application

The XML file looks as follows

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
      <add Name="testdata"/>
  </configSections>
  <connectionStrings>
      <add Name="testdata"/>
  </connectionStrings>
  <ProvidersConfiguration>
    <Providers>
      <add Name="testdata"/>
    </Providers>
  </ProvidersConfiguration>
  <FacadeSettings>
    <Providers>
      <add Name="testdata"/>
    </Providers>
  </FacadeSettings>
</configuration>

now, I've been googling and searching for hours and there's something i'm just not getting. because i can load the file in my script, navigate all the settings, even modify existing values, but that's not what I need to do.

I need to add a section like this

<NewSettings>
    <add Name="setting"/>
  </NewSettings>

so that my config file looks like this

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
      <add Name="testdata"/>
  </configSections>
  <connectionStrings>
      <add Name="testdata"/>
  </connectionStrings>
  <ProvidersConfiguration>
    <Providers>
      <add Name="testdata"/>
    </Providers>
  </ProvidersConfiguration>
  <FacadeSettings>
    <Providers>
      <add Name="testdata"/>
    </Providers>
  </FacadeSettings>
   <NewSettings>
      <add Name="setting"/>
   </NewSettings>
</configuration>

it's the NewSettings section I can't figure out and I'm sure that when I wrap my head around it, I'll go "OH...", but right now I'm banging my head on the wall and could use some help

like image 923
Serge111 Avatar asked May 22 '26 07:05

Serge111


1 Answers

Try this:

# Create xml doc - assumes your xml is file E:\Scratch\test.xml
# If it's already in a variable, use $xml = [xml]$myVariable

$xml = [xml](Get-Content E:\Scratch\test.xml)

# Create new element for <NewSettings>
$newSettings = $xml.CreateElement("NewSettings")

# Create new element for <add>
$add = $xml.CreateElement("add")

# Create attribute "Name", and set its value
$settingsAttribute = $xml.CreateAttribute("Name")
$settingsAttribute.Value = "setting"

# Add attribute to <add>
$add.Attributes.Append($settingsAttribute)

# Add <add> to <NewSettings>
$newSettings.AppendChild($add)

# Add <NewSettings> to <configuration>
$xml.configuration.AppendChild($newSettings)

# Save to file
$xml.Save("E:\Scratch\new.xml")
like image 112
KevinD Avatar answered May 25 '26 02:05

KevinD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!