與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
任何人知道如何使這項工作?
酷,這個作品!替換操作符無法使用的任何原因? – MvdD 2013-02-10 05:20:14
沒有理由不能使用它,但是爲了替換字面值,字符串替換方法更快,並且您在[regex] :: matches()返回的組值中使用了文字值。 – mjolinor 2013-02-10 12:45:19