Accessing environment variables in PowerShell

Getting to environment variables like USERNAME and PATH can be hugely important in scripts and commands. While PowerShell actually makes it quite easy to do so, it doesn't always make it very  obvious  on how to do so. There are basically two ways I use.

Don Jones

April 11, 2011

1 Min Read
ITPro Today logo in a gray background | ITPro Today

Getting to environment variables like USERNAME and PATH can be hugely important in scripts and commands. While PowerShell actually makes it quite easy to do so, it doesn't always make it veryobvious on how to do so. There are basically two ways I use.

The first requires you to remember that, like many other storage systems, the environment variable store is presented as a disk drive in PowerShell. Run cd env: to change to it, or just dir env: to see a list of items. Each environment variable is essentially a file, and the contents of that file is the value for the variable. How do you get the content of a file? get-content env:username - or, if you want to type a bit less, type env:username, the same as you might do for a text file in Cmd.exe. Even shorter is gc env:username, which uses another alias ("gc") for Get-Content.

By the way, the drive name here is ENV. You only add the colon when you're referencing the drive as part of a path, such as in the CD or DIR example.

The second technique is even easier. PowerShell sports a built-in variable, $env, which accesses the environment variable store. Follow it with a colon and the variable name, and you're good to go: $env:username will immediately display the currently logged-on user's name. Invaluable in a logon script! 

No need to look for a special environment variable cmdlet, or to fall back on old-school tricks like COM components. It's all built in, and easier than you might think - once you find it.

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like