【问题标题】:Powershell using -replace to edit a portion of text in a node?Powershell使用-replace编辑节点中的部分文本?
【发布时间】:2018-12-28 22:31:14
【问题描述】:

我正在尝试使用 -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>

下面是我当前的代码设置,用于替换整个字符串,但我更喜欢用“内容”替换“文本”,因此节点现在会说“这里有一些内容”。我尝试使用 -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 powershell


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      如果我理解您的问题,您正在用字符串值替换字符串标记。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-04
        • 1970-01-01
        • 1970-01-01
        • 2015-12-25
        • 2011-09-17
        • 1970-01-01
        相关资源
        最近更新 更多