我有一个任务要更改目录中的一些配置文件,需要更改的文件有7个,全部以“Monitoring_Tran_xx”开头。
停止将 XML 文件视为原始文本 - 它们可以以更高的精度进行解析和处理:)
首先,我们需要将文档解析为 XML,最简单的方法可能是:
$xmlDocument = [xml](Get-Content C:\Path\To\)
由于您有多个具有共同命名模式的文档,我们可能会使用Get-ChildItem
发现磁盘上的文件并循环它们以获取路径:
Get-ChildItem -Path C:\path\to\config\files\Monitoring_Tran_*.ps1 |ForEach-Object {
# read each document from disk with `Get-Content`, convert to [xml]
$xmlDocument = [xml]($_ |Get-Content)
}
接下来,我们需要能够navigate我们的 XML 文档。 PowerShell 对此有本机语法绑定:
$tmConfig = $xmlDocument.Monitor.TransactionMonitoringConfig
或者,你可以使用XPath
也可以使用表达式来导航文档:
$tmConfig = $xmlDocument.SelectSingleNode("/Monitor/TransactionMonitoringConfig")
这些文件中存在某些值(TransactionID="01" AgreedResponseTime="500" SearchProfileID="216"
) 需要更改但不存在于所有 7 个中,并且需要在替换或创建它们之前检查它们是否存在
检查命名属性是否exists在节点上我们可以使用the HasAttribute() method https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlelement.hasattribute:
if($tmConfig.HasAttribute('TransactionID')){
# attribute exists, let's update it!
$tmConfig.SetAttribute('TransactionID', 123) # replace 123 with whatever ID you need
}
另外,如果某个参数等于某个值,例如,我尝试插入一个新参数(使用新项目)如果TemplateType = "4152"
然后在它旁边创建一个新参数"DirectoryPoolID = '3' "
如果您只想在另一个属性具有特定值时向节点添加新属性,则可以使用GetAttribute()
and SetAttribute()
:
if($xmlNode.GetAttribute('TemplateType') -eq "4152"){
$xmlNode.SetAttribute("DirectoryPoolID", 3)
}
完成后,将文档保存回文件:
Get-ChildItem -Path C:\path\to\config\files\Monitoring_Tran_*.ps1 |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 #>
# write document back to disk
$xmlDocument.Save($_.FullName)
}