#PowershellBasics: Using environment variables ($env:ProgramFiles)
3April 6, 2020 by Kenneth Fisher
The other day Kendra Little (blog|twitter) mentioned that she was trying to get a command in Powershell working. Specifically one that used an environment variable (%programfiles(x86)%). Shockingly (not) she figured that part out pretty quickly but I still thought it would make an interesting subject for a blog post.
So to start, in batch, cmdshell, or DOS (whatever you want to call it) you can use certain environment variables in your code. For example %programfiles(x86)% that Kendra mentioned will tell you the location of the Program Files (x86) directory. This is handy because not every system uses C:\Program Files (x86) for that particular set of directories. Some other ones I found include the path for the system and temp directories. Interestingly I did some research and I wasn’t able to find a list of this type of environment variable. They appear to be stored in the registry but weren’t easy to find.
Powershell makes this pretty darn easy. All environment variables are under env:. So you can get that same variable this way: (Technically this is a different variable but I couldn’t figure out how to get the ProgramFiles(x86) to work. The parenthesis kept giving me issues.)
$env:ProgramFiles
And Powershell being what it is getting the list here turned out to be pretty easy:
Set-Location Env: Get-ChildItem
From what I can tell these same variables are also available in cmdshell.
Environment Variables are as easy as 123 to find if you know what to look for…
Method 1
1. Start by opening the Start Search, type in “env”, and choose “Edit the system environment variables”:
2. Click the “Environment Variables…” button.
3. Here you will all of the environment variables and what is more, you can add your own!
Method 2
Also in a cmd window type SET and hit enter. The list of environment variables will be displayed. (This is the old school DOS method.) You can also create and assign a value to a new variable by typing SET VariableName=1234. Beware that setting or creating environment variables using this method the scope is limited to the instance of the cmd window you have open. When you close the cmd window your changes go out of scope along with the cmd window.
WIB
try this
$foo = “$env:ProgramFiles(x86)”
That did it! I also found ${Env:ProgramFiles(x86)} and that worked too. Thanks for the help!