Search code examples
regexpowershellreplaceenvironment-variablestemplate-engine

Replacing regular expression token with environment variable in PowerShell


Having a bit of a fight with PowerShell. I'm trying to replace tokens in a text file with the values of environment variables. For example, suppose my input file looks like this:

Hello [ENV(USERNAME)], your computer name is [ENV(COMPUTERNAME)]
and runs [ENV(OS)]

I've tried the following:

Get-Content test.txt | ForEach {$_ -replace '\[ENV\((\w+)\)\]', "$env:$1" }

This gives the error:

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

I've also tried:

Get-Content test.txt | ForEach {$_ -replace '\[ENV\((\w+)\)\]', [environment]::GetEnvironmentVariable($1) }

But this fails to retrieve the variables and gives me this as output:

Hello , your computer is named
and runs

I've tried to call a function I defined myself, but get another error:

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

Anyone know how to make this work?


Solution

  • I got this:

    $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