【问题标题】:XML config comparison to detect any new key and add the key in existing configXML 配置比较以检测任何新密钥并将密钥添加到现有配置中
【发布时间】:2021-09-06 07:19:39
【问题描述】:

我有两个用于 c# 应用程序的配置文件 (XML):

  • CurrentConfigFile = 此配置文件来自生产环境的运行构建。

  • NewConfigFile = 此配置文件来自新版本,来自 QA 团队。

在部署新版本时,我遇到了这个问题:如果在新版本的 NewConfigFile (xml) 中引入了任何新密钥,那么我手动将 NewConfigFileCurrentConfigFile 进行比较,以查看是否有任何新密钥介绍与否。如果有新的密钥,我手动将其插入CurrentConfigFile

我想编写一个可以为我完成上述任务的 PowerShell 脚本。我是 PowerShell 的新手,我在互联网上做了很多搜索,但没有运气。请在这里帮助我。

【问题讨论】:

  • 但是……这听起来像您的CurrentConfigFile 应该始终是NewConfigFile 的副本?在这种情况下,您可以简单地将 NewConfigFile 复制到 CurrentConfigFile。

标签: xml powershell deployment config


【解决方案1】:

查看Get-ContentCompare-Object cmdlet。 Compare-Object-PassThru 参数将使您能够输出两个文件之间的差异。

Compare-Object -ReferenceObject (Get-Content -Path "current-config-file") -DifferenceObject (Get-Content -Path "new-config-file") -PassThru | Out-File "diff-file"

然后您可以将 current-config-file diff-file 的内容类型转换为 [xml],以便您可以使用一些有用的方法和属性。

$currentXML = [xml](Get-Content -Path "current-config-file")
$diffXml = [xml](Get-Content -Path "diff-file")

假设$diffXml 拥有有效的XML(如下所示),您应该能够在$currentXML 上使用InsertAfter 方法在您需要的位置插入新的XML 数据。查看下面的将新元素插入 XML 文件链接,了解有关如何执行此操作的更多详细信息。

...
    <child>
        <subchild>...</subchild>
    </child>
...

Get-Content
Compare-Object
Inserting new elements into XML files
XmlDocument Class

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多