如何使用Powershell更新文件中的标签

时间:2018-10-31 06:42:12

标签: powershell

我有一个配置文件,它是(test.properties)

文件包括:

<a>aa</a>
<b>bb</b>
<c>ccc</c>
<d>dddd</d>
<Test>Yes</Test>

我想使用Powershell替换test.properties文件中的“ Nope”值。

Existing : <Test>Nope<Test>

 AFter Update it should be 

        <Test>Yes<Test>

如何使用Powershell替换此值?

2 个答案:

答案 0 :(得分:2)

使用替换!下面的代码将读取文件中的内容,并将测试标签替换为新值,然后将内容写回到同一文件中

(Get-Content yourfile.xml).replace("<Test>Nope<Test>", "<Test>Yes<Test>") | Set-Content yourfile.xml

答案 1 :(得分:0)

另一种方法是与MarkusHöglund使用的-replace方法相比,使用基于RegEx的.replace()运算符。

-replace "(?<=<(Test)>).*?(?=</\1)",$custValue

它不关心使用不消耗时间的lookarounds替换文本前后的文字(\ 1在前行中重复分组的(Test))。

(get-Content .\test.properties) -replace "(?<=<(Test)>).*?(?=</\1)",$custValue|
set-Content .\test.properties

BTW不是/前面的结束标记吗?