gpt4 book ai didi

xml - 使用 powershell 编辑 XML

转载 作者:数据小太阳 更新时间:2023-10-29 02:51:26 28 4
gpt4 key购买 nike

好吧,我感觉自己像个大白痴。为了工作中的管理目的,我使用 Powershell 已经有一段时间了。也就是说,编写脚本不是我的强项。

现在,我正在尝试编写一个 PS 脚本,在一堆机器上向 XML 添加一个部分,以添加设置来解决我们在某个应用程序中遇到的问题

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>

现在,我已经在谷歌上搜索了好几个小时,但有些东西我还是没找到。因为我可以在我的脚本中加载文件,导航所有设置,甚至修改现有值,但这不是我需要做的。

我需要添加这样的部分

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

所以我的配置文件看起来像这样

<?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 部分,我确信当我把头绕到它周围时,我会说“哦......”,但现在我正在用头撞墙并且需要一些帮助

最佳答案

试试这个:

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

关于xml - 使用 powershell 编辑 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20646769/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com