使用 powershell 编辑 XML [英] Editing XML with powershell
问题描述
好吧,我觉得这里真是个大白痴.为了工作中的管理目的,我一直在使用 Powershell.也就是说,编写脚本并不是我的强项.
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.
现在,我正在尝试编写一个 PS 脚本,将一个部分添加到一堆机器上的 XML 中,以添加设置来解决我们在某个应用程序中遇到的问题
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
XML 文件如下所示
<?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>
这是我无法弄清楚的 NewSettings 部分,我确定当我将头环绕在它周围时,我会说哦...",但现在我正在用头撞墙并且可以使用一些帮助
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
推荐答案
试试这个:
# 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")
这篇关于使用 powershell 编辑 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!