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
to change to it, or just
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?
- or, if you want to type a bit less,
, the same as you might do for a text file in Cmd.exe. Even shorter is
, 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
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:
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.