Search code examples
powershellenvironment-variablesindirection

Get the value of an environment variable whose name is stored in a variable


I am trying to figure out an easy to read and understandable idiom that evaluates the the value of an environment variable whose name is stored in a variable:

$varName='TEMP'

I have come up with

$val = invoke-expression "`$env:$varName"

and am wondering if there is a more to the point alternative.


Solution

  • env: a real PSDrive that supports item retrieval:

    $val = (Get-Item -Path env:\$varName).Value