Powershell使用-replace编辑节点中的一部分文本?

时间:2018-12-28 22:31:15

标签: xml powershell

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

以下是一些我要根据'Path'值进行编辑的示例节点:

<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)

2 个答案:

答案 0 :(得分:2)

使用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运算符执行正则表达式替换。

答案 1 :(得分:0)

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

如果是这样,您可以将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')