Replace regex token environment variable in PowerShell

A bit of a PowerShell duel. I am trying to replace tokens in a text file with environment variable values. 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 an 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 that doesn't get the variables and gives me this as output:

Hello , your computer is named
and runs

      

I tried to call a function that I defined myself, but I 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

      

Does anyone know how to make this work?

+3


source to share


3 answers


I got it:



$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

      

+2


source


"$env:$1"

Use '$env:$1'

(single quotes) instead of (double quotes) and you should be fine. PowerShell will expand variables in a double quoted string. $1

Not a PowerShell variable in your context : it's a regex token.



0


source


Instead, [ENV(...)]

why not use %...%

?

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

      

Which gives me: Hi IanG, your computer name is 1EUKCOL1184 and starts Windows_NT

0


source







All Articles