Blog Post

#PowershellBasics: Using environment variables ($env:ProgramFiles)

,

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.

Original post (opens in new tab)
View comments in original post (opens in new tab)

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating