与 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
任何人都知道如何使这项工作?