繁体   English   中英

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

[英]Powershell using -replace to edit a portion of text in a node?

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM