3

与 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

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

4

3 回答 3

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
于 2013-02-10T03:18:56.713 回答
0

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

于 2013-02-10T15:19:41.153 回答
0

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

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

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

于 2017-11-23T22:36:26.013 回答