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 更喜欢将"文本"替换为"内容",因此节点现在将显示"此处的一些内容"。我尝试使用 -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)

使用 XML 数据时,XPath 通常是访问节点及其属性的最通用方式。在您的情况下,您希望选择<Configuration>节点的<ConfiguredValue>子节点,该节点的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 运算符执行正则表达式替换。

如果我理解您的问题,您将用字符串值替换字符串令牌。

如果这是真的,您可以将 xml 视为字符串并执行如下所示的替换:

$token = 'text'
$value = 'content'
$content = Get-Content $file.FullName
$content = $content.Replace($token, $value)
$content | Out-File $file.FullName
请记住,令牌

应该是唯一的,因为它将替换令牌的所有实例。

如果无法标识唯一标记,则可以在从 xml 路径中选择值后对字符串执行替换操作。

(($xml.DTSConfiguration.Configuration | Where-Object {$_.Path -like ("*{0}*" -f $pathVar)}).ConfiguredValue = ("{0}" -f $confVal)).Replace('text','content')

最新更新