尝试在powershell中结合替换和新项目 [英] Trying to combine replace and new-item in powershell
问题描述
我有一个任务要修改目录中的一些配置文件,需要修改的文件有7个,都是以Monitoring_Tran_xx"开头的.
在这些文件中,某些值 (TransactionID=01"AgreedResponseTime=500"SearchProfileID=216")
需要更改但不会出现在所有 7 个文件中,并且需要在替换或创建它们之前检查它们是否存在.此外,如果某个参数等于某个值,例如,我试图插入一个新参数(使用 new-item)如果 TemplateType = "4152"
然后在它旁边创建一个新参数 "DirectoryPoolID = '3' "
感谢您对此的帮助.
谢谢
以下配置文件示例:
<监视器><配置操作模式=事务";LogFileName=C:\Program Files\*******s\MonitoringOMTR\MonitorLog_01.log";WriteFileInterval=120"连接密钥=*********"/><TransactionMonitoringConfig TransactionID="01";AgreeedResponseTime=500"SearchProfileID =216"/><显示消息><消息名称=MOISearchStart"/><消息名称=MOOSearchFound"/><消息名称=MOOSearchEnd"/><消息名称=MOOAlert"/></ShowMessages><PerformanceCounters TransactionCount=191";TransactionBreaches=0"/></监视器>
我尝试过但效果不佳的 Powershell 脚本:
(Get-Content -Path '***FS2072\UserData$\aroyet01\Desktop\HostPS.txt') |if ([bool]((Get-Content -Path "***FS2072\UserData$\aroyet01\Desktop\HostPS.txt") -like '*DirectoryPool*', '*SearchProfile*')) {写主机找到它"}别的 {写主机没有找到";}ForEach-Object {$_ -replace 'TransactionCount="191"', 'TransactionCount="196"'} |Set-Content -Path '***FS2072\UserData$\aroyet01\Desktop\HostPS.txt'Get-Content -Path '***FS2072\UserData$\aroyet01\Desktop\HostPS.txt'
我有一个任务要修改目录中的一些配置文件,需要修改的文件有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 {# 使用`Get-Content`从磁盘读取每个文档,转换为[xml]$xmlDocument = [xml]($_ |Get-Content)}
接下来,我们需要能够导航我们的 XML 文档.PowerShell 对此具有本机语法绑定:
$tmConfig = $xmlDocument.Monitor.TransactionMonitoringConfig
或者,您也可以使用 XPath
表达式来导航文档:
$tmConfig = $xmlDocument.SelectSingleNode("/Monitor/TransactionMonitoringConfig")
<块引用>
在这些文件中,某些值(TransactionID=01"AgreedResponseTime=500"SearchProfileID=216"
)需要更改但不会出现在所有 7 个文件中,并且需要在替换或创建它们之前检查它们是否存在
要检查节点上是否存在命名属性,我们可以使用HasAttribute()
方法:
if($tmConfig.HasAttribute('TransactionID')){# 属性存在,让我们更新它!$tmConfig.SetAttribute('TransactionID', 123) # 用你需要的任何 ID 替换 123}
<块引用>
此外,如果某个参数等于某个值,例如,我试图插入一个新参数(使用 new-item)如果 TemplateType = "4152"
然后在它旁边创建一个新参数 "DirectoryPoolID = '3' "
如果您只想在另一个属性具有特定值时向节点添加新属性,则可以使用 GetAttribute()
和 SetAttribute()
:
if($xmlNode.GetAttribute('TemplateType') -eq "4152"){$xmlNode.SetAttribute("DirectoryPoolID", 3)}
完成后,将文档保存回文件:
Get-ChildItem -Path C:\path\to\config\files\Monitoring_Tran_*.ps1 |ForEach-Object {# 使用`Get-Content`从磁盘读取每个文档,转换为[xml]$xmlDocument = [xml]($_ |Get-Content)<#在这里编写所有代码来检查和更新属性#># 将文件写回磁盘$xmlDocument.Save($_.FullName)}
I have a task to make changes to some Config files in a Directory, and the files that need changing are 7, all starting with "Monitoring_Tran_xx".
Within these files there are certain values (TransactionID="01" AgreedResponseTime="500" SearchProfileID="216")
that need changing but not present across all 7, and will need to check if they are present before replace or creating them.
Also I am trying to insert a new parameter(using new-item) if a certain parameter is equal to a certain value e.g. if TemplateType = "4152"
then create a new parameter next to it "DirectoryPoolID = '3' "
I will appreciate your help on this please.
Thanks
Example of Config file below:
<?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" />
<ShowMessages>
<Message Name="MOISearchStart" />
<Message Name="MOOSearchFound" />
<Message Name="MOOSearchEnd" />
<Message Name="MOOAlert" />
</ShowMessages>
<PerformanceCounters TransactionCount="191" TransactionBreaches="0" />
</Monitor>
Powershell script that i tried but it didn't quite result well:
(Get-Content -Path '***FS2072\UserData$\aroyet01\Desktop\HostPS.txt') |
if ([bool]((Get-Content -Path "***FS2072\UserData$\aroyet01\Desktop\HostPS.txt") -like '*DirectoryPool*', '*SearchProfile*')) {
write-host "Found it"
}
else {
write-host "Did not find it"
}
ForEach-Object {$_ -replace 'TransactionCount="191"', 'TransactionCount="196"'} |
Set-Content -Path '***FS2072\UserData$\aroyet01\Desktop\HostPS.txt'
Get-Content -Path '***FS2072\UserData$\aroyet01\Desktop\HostPS.txt'
I have a task to make changes to some Config files in a Directory, and the files that need changing are 7, all starting with "Monitoring_Tran_xx".
Stop treating your XML files as raw text - they can be parsed and treated with much better precision :)
First up, we need to parse the document(s) as XML, the easiest way probably being:
$xmlDocument = [xml](Get-Content C:\Path\To\)
Since you have multiple documents with a common naming pattern, we might use Get-ChildItem
to discover the files on disk and loop over them to get the paths:
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)
}
Next, we need to be able to navigate our XML document. PowerShell has native syntax bindings for this:
$tmConfig = $xmlDocument.Monitor.TransactionMonitoringConfig
or, you can use XPath
expressions to navigate the document as well:
$tmConfig = $xmlDocument.SelectSingleNode("/Monitor/TransactionMonitoringConfig")
Within these files there are certain values (
TransactionID="01" AgreedResponseTime="500" SearchProfileID="216"
) that need changing but not present across all 7, and will need to check if they are present before replace or creating them
To check whether a named attribute exists on a node we can use the HasAttribute()
method:
if($tmConfig.HasAttribute('TransactionID')){
# attribute exists, let's update it!
$tmConfig.SetAttribute('TransactionID', 123) # replace 123 with whatever ID you need
}
Also I am trying to insert a new parameter(using new-item) if a certain parameter is equal to a certain value e.g. if
TemplateType = "4152"
then create a new parameter next to it"DirectoryPoolID = '3' "
In the case where you want to add a new attribute to a node only if another attribute has a specific value, you can use GetAttribute()
and SetAttribute()
:
if($xmlNode.GetAttribute('TemplateType') -eq "4152"){
$xmlNode.SetAttribute("DirectoryPoolID", 3)
}
Whenever you're done, save the document back to file:
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)
}
这篇关于尝试在powershell中结合替换和新项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!