Search code examples
powershellvariablesexpansion

variable expansion inside namespace-qualified variable name


Problem

I want to perform parametric variable evaluation. The to-be-evaluated variable name is constructed with a string concatenation - from a namespace part and a name part being defined in a variable. Example: env:$var, where the value of $var is, for instance "OS". However, while using the expression

${env:OS}

gives the expected value Windows_NT, the construct

$var="OS"
${env:$var}

is a null-valued expression.

Motivation

I'm not really intereseted in the value of environment variables (but this was the simplest example, I could find). What I really want, is to refer to the content of a file via the ${c:<filename>} construct. I want to perform several, conditional in-file string substitutions and, I'd like to use a construct similar to this:

<identify files in a foreach>
${c:<filename>} -replace 'this', 'that' > ${c:<new filename>}

To achieve this, I need <filename> to be a value of an iterator variable.

Question

If the value of $var is OS, what shall be at ..., if I expect the value of the following expression to be Windows_NT?

${env:...var...}

Solution

  • Use Get-ChildItem on the env: PSDrive and expand the Value of the result:

    (ls env:$var).Value
    

    Edit: As @PetSerAl suggested in the comments using Get-Content is a more elegant approach:

    (cat env:$var)