使用Powershell在配置文件中查找和替换$

时间:2015-02-27 22:10:44

标签: xml powershell

哦,嘿,

所以我有一些xml配置文件,我想在其中找到“$ Machine_Name $”的特定关键字,并将其替换为来自数据库的IP地址。

所以我能够从数据库中获取正确的信息,但是我遇到了能够在XML配置文件中专门替换$ Machine_Name $ Hook的问题。

<add key="blah" value="soap.tcp://$Machine_Name$:PORT/blah" />
<add key="blah2" value="soap.tcop//$Machine_Name$:PORT/blahblah" />
<add key="blah3" value="soap.tcop//$Machine_Name$:PORT/blahblahblah" />

我有大约50多行与此类似,我想查找和替换$ Machine_Name $ Hook。在这个例子中,我不认为Get-Content [xml] file.exe.config和做节点搜索和替换会给我带来任何东西。我必须在Powershell中构建所有字符串,如果它们中的任何一个发生变化,那么我将不得不重做我的脚本,其中$ Machine_Name $ Hook将始终存在。

无论如何,到目前为止我尝试过的似乎不起作用:

(Get-Content C:\Test\Project.exe.config)  
| ForEach-Object {$_ -replace "$Machine_Name$" , "*"} 
| Set-Content C:\Test\Project.exe.config  

非常感谢任何帮助!

好的伙计们,对不起......我想通了......

因为$是Powershell中的保留字符,所以我不能公开地替换它。我不得不从$'s

中添加\ in
(Get-Content C:\Test\Project.exe.config) 
| ForEach-Object {$_ -replace '\$Machine_Name\$', "IP" } 
| Set-Content C:\Test\Project.exe.config 

1 个答案:

答案 0 :(得分:1)

由于您只是进行文字匹配和替换,因此可以使用字符串.Replace()方法。它更简单,如果您使用foreach上的-Raw开关将其作为单个字符串读取,则不需要Get-Content

(Get-Content C:\Test\Project.exe.config -Raw).Replace('$Machine_Name$','IP') | 
 Set-Content C:\Test\Project.exe.config