PowerShell with a Purpose Blog

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 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.

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.