Environment variable names with parentheses, like %ProgramFiles(x86)%, in PowerShell?

Posted by jwfearn on Stack Overflow See other posts from Stack Overflow or by jwfearn
Published on 2011-01-11T01:51:26Z Indexed on 2011/01/11 1:53 UTC
Read the original article Hit count: 509

How does one get the value of environment variable whose name contains parentheses in a PowerShell script?

To complicate matters, some variables names contains parentheses while others have similar names without parenteses. For example (using cmd.exe):

C:\>set | find "ProgramFiles"
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)

We see that %ProgramFiles% is not the same as %ProgramFiles(x86)%.

My PowerShell code is failing in a weird way because it's ignoring the part of the environment variable name after the parentheses. Since this happens to match the name of a different, but existing, environment variable I don't fail, I just get the right value of the wrong variable.

Here's a test function in the PowerShell scripting language to illustrate my problem:

function Do-Test
{
    $ok = "C:\Program Files (x86)"       # note space between 's' and '(
    $bad = "$Env:ProgramFiles" + "(x86)" # uses %ProgramFiles%

    $bin32 = "$Env:ProgramFiles(x86)"    # LINE 6, I want to use %ProgramFiles(x86)%

    if ( $bin32 -eq $ok ) {
        Write-Output "Pass"
    } elseif ( $bin32 -eq $bad ) {
        Write-Output "Fail: %ProgramFiles% used instead of %ProgramFiles(x86)%"
    } else {
        Write-Output "Fail: some other reason"
    }
}

And here's the output:

PS> Do-Test
Fail: %ProgramFiles% used instead of %ProgramFiles(x86)%

Is there a simple change I can make to line 6 above to get the correct value of %ProgramFiles(x86)%?

*NOTE: In the text of this post I am using batch file syntax for environment variables as a convenient shorthand. For example %SOME_VARIABLE% means "the value of the environment variable whose name is SOME_VARIABLE". If I knew the properly escaped syntax in PowerShell, I wouldn't need to ask this question.*

© Stack Overflow or respective owner

Related posts about powershell

Related posts about environment-variables