4

我正在将数千行批处理代码转换为 PowerShell。我正在使用正则表达式来帮助完成这个过程。问题是代码的一部分是:

$`$2

替换时,它只显示$2并且不会扩展变量。我还在替换的第二部分使用了单引号,而不是转义变量,结果相同。

$origString = @'
IF /I "%OPERATINGSYSTEM:~0,6%"=="WIN864" SET CACHE_OS=WIN864
...many more lines of batch code
'@

$replacedString = $origString -replace "(IF /I `"%)(.+)(:.+%`"==`")(.+`")(.+)","if ( $`$2 -match `"^`$4 ) {`$5 }"

$replacedString
4

2 回答 2

8

你可以尝试这样的事情:

$origString -replace "(IF /I `"%)(.+)(:.+%`"==`")(.+`")(.+)",'if ($$$2 -match "^$4" ) {$5 }'

注意$$$2. 这评估为$和 的内容$2


一些代码向您展示差异。自己试试:

'abc' -replace 'a(\w)', '$1'
'abc' -replace 'a(\w)', "$1"  # "$1" is expanded before replace to ''
'abc' -replace 'a(\w)', '$$$1'
'abc' -replace 'a(\w)', "$$$1" #variable $$ and $1 is expanded before regex replace
                               #$$ and $1 don't exist, so they are expanded to ''

$$ = 'xyz'
$1 = '123'
'abc' -replace 'a(\w)', "$$$1`$1" #"$$$1" is expanded to 'xyz123', but `$1 is used in regex
于 2012-02-22T19:48:58.430 回答
0

试试这样:

 $replacedString = $origString -replace "(IF /I `"%)(.+)(:.+%`"==`")(.+`")(.+)","if ( $`$`$2 -match `"^`$4 ) {`$5 }"
于 2012-02-22T19:51:46.040 回答