首页 > 解决方案 > 目录中的类似 XML 配置文件需要更新 - 在 SingleNode 中添加新属性和替换现有属性

问题描述

我的任务是对目录中的一些配置文件进行更改,需要更改的文件有 7 个,均以“Monitoring_Tran_xx”开头。在这些文件中,有某些值 (TransactionID="01" AgreedResponseTime="500" SearchProfileID="216") 需要更改但不存在于所有 7 个文件中,并且需要在替换或创建它们之前检查它们是否存在。如果某个参数等于某个值,我也尝试插入一个新参数(使用新项目),例如如果 TemplateType =“4152”,然后在它旁边创建一个新参数“DirectoryPoolID = '3'”

我会很感激你在这方面的帮助。

谢谢

配置文件示例如下:

<?xml *version="1.0"* ?>
<Monitor>
    <Configuration OperatingMode="Transaction" LogFileName="C:\Program Files\*******s\MonitoringOMTR\MonitorLog_01.log" WriteFileInterval="120" ConnectionKey="**********" />
    <TransactionMonitoringConfig TransactionID="01" AgreedResponseTime="500" SearchProfileID="216" TemplateType="4152" />
    <ShowMessages>
        <Message Name="MOISearchStart" />
        <Message Name="MOOSearchFound" />
        <Message Name="MOOSearchEnd" />
        <Message Name="MOOAlert" />
    </ShowMessages>
    <PerformanceCounters TransactionCount="191" TransactionBreaches="0" />
</Monitor>

我尝试过但效果不佳的 Powershell 脚本:

Get-ChildItem -Path D:\Timmy\OMTR\Monitor_Transaction_* |ForEach-Object {
  # read each document from disk with `Get-Content`, convert to [xml]
  $xmlDocument = [xml]($_ |Get-Content)

  <# write all the code to inspect and update the attributes here #>

  $tmConfig = $xmlDocument.SelectSingleNode("/Monitor/TransactionMonitoringConfig")
  
 

  if($tmConfig.HasAttribute('TransactionID')){
  # attribute exists, let's update it!
  $tmConfig.SetAttribute('TransactionID', 650) # replace 123 with whatever ID you need

  $xmlNode = $xmlDocument.SelectSingleNode("/Monitor/TransactionMonitoringConfig")

  if($xmlNode.GetAttribute('TemplateType') -eq "4152")
{
  $xmlNode.AddAttribute([System.xml.xmlNode] "DirectoryPoolID = '3'")
}

}
 # write document back to disk
  $xmlDocument.Save($_.FullName)
}

标签: xmlpowershell

解决方案


推荐阅读