【问题标题】:Updating config xml file and save it using powershell更新配置 xml 文件并使用 powershell 保存
【发布时间】:2015-02-11 20:11:19
【问题描述】:

我需要更新此配置文件,以使“newVersion”的所有值都需要更新为单个值。

<configuration>
<runtime>
<assemblyBinding>
  <dependentAssembly>
        <assemblyIdentity name="A" 
publicKeyToken="5d861ad8ad8cd06f" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-65534.65534.65534.65534" newVersion="4.0.0.103" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="B" publicKeyToken="ae714df8cd90bc8f" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-65534.65534.65534.65534" newVersion="4.0.0.103" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="C" publicKeyToken="22955931b98512b6" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-65534.65534.65534.65534" newVersion="4.0.0.103" />
      </dependentAssembly>
      <dependentAssembly>
                <assemblyIdentity name="D"
                                  publicKeyToken="585a888b4a9ba2e3"
                                  culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-65534.65534.65534.65534"
                                 newVersion="2.5.0.1286"/>

              </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
  </startup>
</configuration>

我在下面试过这个

$appconfig='file location'
$doc = (Get-Content $appconfig) -as [Xml]
$obj = $doc.configuration.runtime.assemblyBinding.dependentAssembly
$obj2 = $obj.assemblyIdentity | where {$_.name -eq 'D'}
$obj.bindingRedirect.newVersion="1.1.1.1"
echo $obj.bindingRedirect.newVersion
$doc.Save($appconfig)

我知道这只会更改为“D”部分,如何也更改为上述 A、B 和 C。感谢您的帮助!

【问题讨论】:

    标签: xml powershell config


    【解决方案1】:
    (gc C:\temp\config.xml) -replace '(newversion=)".*?"' ,'$1"1.1.1.1"' # if you want to save the file add |sc c:\temp\config.xml
    

    【讨论】:

    • 'newversion=.*' 也将匹配并替换结束的“/>”,从而使您的 XML 文件无效。我宁愿使用:(gc C:\temp\config.xml) -replace '(newversion=)".*?"', '$1"1.1.1.1"'.
    • 请记住,这将替换“newversion”的所有出现的值,无论它是哪个节点的属性。 @dotnetom 的回答更省钱。
    • @ManuelBatsching 感谢您的评论。顺便说一句,操作员说他想替换所有发生的事情并且没有提到任何限制。我认为在这种情况下使用替换更直观。
    • 谢谢 Manuel 和 Kayasax,是的,即使关闭 "/>" 也被替换了,我只是立即添加了 'newversion="%buildnumber%/>"'。但是,我应该如何理解 -replace '(newversion=)".*?"', '$1"1.1.1.1"'.. 如果问号只代表一个字符,那么我认为 /> 是 2 个字符对...纠正我..我可能完全错了...再次感谢你们俩..
    • 正则表达式.*"中的star-quantor是贪婪的,这意味着它会尽可能匹配。在您的情况下,它将匹配任何字符,直到找到该行中的最后一个 "。仅当newversion="someValue" 是该行中的最后一个属性时,这在上面的示例中才有效。如果不是,它会再次弄乱您的 XML 文档,因为它还会匹配 newversion 之后的任何属性。 ? 通过将星量子的行为更改为“非贪婪”来消除这种危险。所以我想鼓励你保留?
    猜你喜欢
    • 2017-12-19
    • 2010-12-15
    • 1970-01-01
    • 2022-08-19
    • 2010-11-06
    • 1970-01-01
    • 2011-08-27
    • 2011-01-28
    • 2020-03-07
    相关资源
    最近更新 更多