首页 > 解决方案 > Powershell使用-replace编辑节点中的部分文本?

问题描述

我正在尝试使用 -replace 或等效于根据条件搜索指定节点的东西来编写 powershell 脚本,并仅将部分文本替换为其他文本。这甚至可能吗?

这是我尝试根据“路径”的值编辑的一些示例节点:

<Configuration ConfiguredType="Property" Path="\Package.Variables[User::var1].Properties[Value]" 
    ValueType="String">
        <ConfiguredValue>Some Text Here</ConfiguredValue>
</Configuration>

<Configuration ConfiguredType="Property" Path="\Package.Variables[User::var2].Properties[Value]" 
    ValueType="String">
        <ConfiguredValue>More Text Here</ConfiguredValue>
</Configuration>

下面是我当前的代码设置,用于替换整个字符串,但 id 更喜欢用“content”替换“text”,因此节点现在会说“Some Content Here”。我尝试使用 -replace 但我无法让它正常工作。

#defaults
$xml = [xml](Get-Content $file.FullName)
$node = $xml.DTSConfiguration.Configuration

#updating individual attributes

$pathVar = "var1"
$confVal = ""
($xml.DTSConfiguration.Configuration | Where-Object {$_.Path -like ("*{0}*" -f $pathVar)}).ConfiguredValue = ("{0}" -f $confVal)
$xml.Save($file.FullName)

标签: xmlpowershell

解决方案


处理 XML 数据时,XPath通常是访问节点及其属性的最通用方式。在您的情况下,您希望选择其属性包含变量中定义的子字符串<ConfiguredValue>的节点的子节点。<Configuration>Path$pathVar

$xpath = "//Configuration[contains(@Path, '$pathVar')]/ConfiguredValue"
$node  = $xml.SelectSingleNode($xpath)
$node.'#text' = $node.'#text'.Replace('Text', 'Content')

请注意,XPath 表达式和Replace()方法都区分大小写。

也可以使用-replace运算符(默认情况下不区分大小写):

$node.'#text' = $node.'#text' -replace 'Text', 'Content'

但是,该Replace()方法提供了更好的性能,因为它执行简单的字符串替换,而-replace运算符执行正则表达式替换。


推荐阅读