Powershell替换字符串中的变量

时间:2014-09-15 13:01:38

标签: powershell sitecore sitecore-rocks

我在配置文件中有一个包含$字符的字符串 我想替换这一行,但powershell将其识别为变量 我做了一些研究,发现“”=变量和''=正则表达式 并且使用反引号`应该可以工作,但是我无法使它工作。

要替换的行:

<remove folder="$(dataFolder)/logs" pattern="log.*.txt" maxCount="20" minAge="7.00:00:00" />

替换为:

<remove folder="$(dataFolder)/logs" pattern="log.*.txt" maxCount="20" minAge="7.00:00:00"/>\n          <remove folder="$(dataFolder)/logs" pattern="WebDAV.log.*.txt" maxCount="20" minAge="7.00:00:00" />

我现在有什么:

$replace = '<remove folder="$(dataFolder)/logs" pattern="log.*.txt" maxCount="20" minAge="7.00:00:00"/>';
$with = ('<remove folder="$(dataFolder)/logs" pattern="log.*.txt" maxCount="20"    minAge="7.00:00:00"/>\n          <remove folder="$(dataFolder)/logs" pattern="WebDAV.log.*.txt" maxCount="20" minAge="7.00:00:00" />');
(Get-Content $webConfigFileName) -replace $replace,$with | Set-Content $webConfigFileName;
Write-Output "Replaced '$replace' with '$with' in $webConfigFileName";

有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:3)

在大多数情况下,您可以使用单引号将其中的所有内容视为文字,而不是解释变量等内容。在某些情况下,使用多个嵌套引号可能会出现问题,在这种情况下,您需要开始转义或使用here字符串,但在这种情况下,它不是必需的。

实际上,您需要在匹配语句中使用正则表达式转义符以使其工作,然后将所有内容包装在单引号中以使其正常工作。

$1 = '<remove folder="$(dataFolder)/logs" pattern="log.*.txt" maxCount="20" minAge="7.00:00:00" />'
$REGEX = '<remove folder="\$\(dataFolder\)\/logs" pattern="log\.\*\.txt" maxCount="20" minAge="7\.00:00:00" \/>'
$1 -replace $regex,'test'

编辑:您要替换的txt也可以用单引号括起来,它会起作用,如下所示:

$1=gc C:\test.txt
$REGEX = '<remove folder="\$\(dataFolder\)\/logs" pattern="log\.\*\.txt" maxCount="20" minAge="7\.00:00:00" \/>'
$replace = '<remove folder="$(dataFolder)/logs" pattern="log.*.txt" maxCount="20" minAge="7.00:00:00"/>          
<remove folder="$(dataFolder)/logs" pattern="WebDAV.log.*.txt" maxCount="20" minAge="7.00:00:00" />'
$1 -replace $regex,$replace | set-content c:\test.txt

答案 1 :(得分:2)

尝试使用here-strings和Replace方法的组合:

$with = @"
<remove folder="`$(dataFolder)/logs" pattern="log.*.txt" maxCount="20" minAge="7.00:00:00" />
<remove folder="`$(dataFolder)/logs" pattern="WebDAV.log.*.txt" maxCount="20" minAge="7.00:00:00" />
"@

$replace = @"
<remove folder="`$(dataFolder)/logs" pattern="log.*.txt" maxCount="20" minAge="7.00:00:00" />
"@

(Get-Content $webConfigFileName).replace($replace,$with) | Out-String | Set-Content $webConfigFileName;

Write-Output "Replaced '$replace' with '$with' in $webConfigFileName";

答案 2 :(得分:0)

如果工作,请尝试此操作

 $repl ='(<remove folder="\$\(dataFolder\)/logs" pattern=")((?:log)\.\*\.txt)(" maxCount="20" minAge="7.00:00:00" \/>)'

(Cat $webConfigFileName) -replace $repl,"`$0`n`t`$1WebDAV.`$2`$3"| Set-Content $webConfigFileName;