Tuesday, 15 May 2012

regex - Replacing regular expression token with environment variable in PowerShell -



regex - Replacing regular expression token with environment variable in PowerShell -

having bit of fighting powershell. i'm trying replace tokens in text file values of environment variables. example, suppose input file looks this:

hello [env(username)], computer name [env(computername)] , runs [env(os)]

i've tried following:

get-content test.txt | foreach {$_ -replace '\[env\((\w+)\)\]', "$env:$1" }

this gives error:

at line:1 char:74 + get-content test.txt | foreach {$_ -replace '\[env\((\w+)\)\]', "$env:$1 ... + ~~~~~ variable reference not valid. ':' not followed valid variable name character. consider using ${} delimit name. + categoryinfo : parsererror: (:) [], parentcontainserrorrecordexception + fullyqualifiederrorid : invalidvariablereferencewithdrive

i've tried:

get-content test.txt | foreach {$_ -replace '\[env\((\w+)\)\]', [environment]::getenvironmentvariable($1) }

but fails retrieve variables , gives me output:

hello , computer named , runs

i've tried phone call function defined myself, error:

at d:\tfs\hipv3\prod\dev\tools\environmentresolve.ps1:13 char:72 + get-content test.txt | foreach {$_ -replace '\[env\((\w+)\)\]', getenvva ... + ~~~~~~~~ missing look after ','. @ d:\tfs\hipv3\prod\dev\tools\environmentresolve.ps1:13 char:73 + get-content test.txt | foreach {$_ -replace '\[env\((\w+)\)\]', getenvva ... + ~~~~~~~~ unexpected token 'getenvvar' in look or statement. + categoryinfo : parsererror: (:) [], parseexception + fullyqualifiederrorid : missingexpressionaftertoken

anyone know how create work?

i got this:

$string = 'hello [env(username)], computer name [env(computername)] , 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 replace environment-variables template-engine

No comments:

Post a Comment