Environment variable names with parentheses, like %ProgramFiles(x86)%, in PowerShell?
Simple. Change line 6 to remove the spaces inside the brackets:
$d = "${Env:ProgramFiles(x86)}" # LINE 6 (NO spaces inside brackets)
You just have to wrap the variable that contains () with {}. No spaces inside the brackets.
jwfearn
Updated on July 10, 2022Comments
-
jwfearn over 1 year
In a PowerShell script, how does one get the value of an environment variable whose name contains parentheses?
To complicate matters, some variables' names contains parentheses while others have similar names without parentheses. 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% $d = "${ Env:ProgramFiles(x86) }" # fail (2), LINE 6 # $d = "$Env:ProgramFiles(x86)" # fail (1) if ( $d -eq $ok ) { Write-Output "Pass" } elseif ( $d -eq $bad ) { Write-Output "Fail: (1) %ProgramFiles% used instead of %ProgramFiles(x86)%" } else { Write-Output "Fail: (2) some other reason" } }
And here's the output:
PS> Do-Test Fail: (2) some other reason
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.