与 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
有人知道怎么做吗?
最佳答案
我明白了:
$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
关于regex - 在 PowerShell 中用环境变量替换正则表达式 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14793973/