在PowerShell中用环境变量替换正则表达式标记

时间:2013-02-10 02:13:12

标签: regex powershell replace environment-variables template-engine

与PowerShell进行一些斗争。我正在尝试使用环境变量的值替换文本文件中的标记。例如,假设我的输入文件如下所示:

Hello [ENV(USERNAME)], your computer name is [ENV(COMPUTERNAME)]
and runs [ENV(OS)]

我尝试了以下内容:

Get-Content test.txt | ForEach {$_ -replace '\[ENV\((\w+)\)\]', "$env:$1" }

这给出了错误:

At line:1 char:74
+ Get-Content test.txt | ForEach {$_ -replace '\[ENV\((\w+)\)\]', "$env:$1 ...
+                                                                  ~~~~~
Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : InvalidVariableReferenceWithDrive

我也试过了:

Get-Content test.txt | ForEach {$_ -replace '\[ENV\((\w+)\)\]', [environment]::GetEnvironmentVariable($1) }

但是这无法检索变量并将其作为输出:

Hello , your computer is named
and runs

我试图调用我自己定义的函数,但得到另一个错误:

At D:\tfs\HIPv3\prod\Dev\Tools\EnvironmentResolve.ps1:13 char:72
+ Get-Content test.txt | ForEach {$_ -replace '\[ENV\((\w+)\)\]', GetEnvVa ...
+                                                                 ~~~~~~~~
Missing expression after ','.
At D:\tfs\HIPv3\prod\Dev\Tools\EnvironmentResolve.ps1:13 char:73
+ Get-Content test.txt | ForEach {$_ -replace '\[ENV\((\w+)\)\]', GetEnvVa ...
+                                                                 ~~~~~~~~
Unexpected token 'GetEnvVar' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : MissingExpressionAfterToken

任何人都知道如何使这项工作?

3 个答案:

答案 0 :(得分:2)

我明白了:

$string = 'Hello [ENV(USERNAME)], your computer name is [ENV(COMPUTERNAME)] and runs [ENV(OS)]'

$regex = '\[ENV\(([^)]+)\)]'

 [regex]::Matches($string,$regex) |
  foreach {
            $org = $_.groups[0].value
            $repl = iex ('$env:' + $_.groups[1].value)
            $string = $string.replace($org,$repl)
          }

 $string

答案 1 :(得分:0)

而不是"$env:$1"(双引号)使用'$env:$1'(单引号),你应该没问题。 PowerShell将扩展双引号字符串中的变量。在您的上下文中,$1 不是 PowerShell变量:它是正则表达式标记。

答案 2 :(得分:0)

而不是[ENV(...)]为什么不使用%...%

$string = 'Hello %USERNAME%, your computer name is %COMPUTERNAME% and runs %OS%'
[System.Environment]::ExpandEnvironmentVariables($string)

这给了我: 您好IanG,您的计算机名称是1EUKCOL1184并运行Windows_NT