3

與PowerShell爭執不休。我試圖用環境變量的值替換文本文件中的標記。例如,假設我輸入文件看起來像這樣:在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) } 

但是這不能檢索t他變量,給了我這樣的輸出:

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 

任何人知道如何使這項工作?

回答

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 
+0

酷,這個作品!替換操作符無法使用的任何原因? – MvdD 2013-02-10 05:20:14

+0

沒有理由不能使用它,但是爲了替換字面值,字符串替換方法更快,並且您在[regex] :: matches()返回的組值中使用了文字值。 – mjolinor 2013-02-10 12:45:19

0

而不是"$env:$1"(雙引號)使用'$env:$1'(單引號),你應該確定。 PowerShell將在雙引號字符串中展開變量。在你的上下文中$1而不是一個PowerShell變量:它是一個正則表達式令牌。

+0

但是,這並沒有給出所需的輸出。我需要它用環境變量的值替換標記。您的解決方案(我在發佈之前嘗試過)給出以下輸出:Hello $ env:USERNAME,您的計算機名爲$ env:COMPUTERNAME 並運行操作系統:$ env:OS – MvdD 2013-02-11 04:21:28

0

而不是[ENV(...)]爲什麼不使用%...%

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

這給了我: IANG您好,您的計算機名稱是1EUKCOL1184並運行Windows_NT