PowerShell How-To

How To Work with Environment Variables in PowerShell

Windows environment variables give system administrators access to a plethora of information about the Windows operating system.

Separated into system and user-level scopes, default environment variables can be read and modified, and new environment variables can be also added.

Let's see how we can manage environment variables with PowerShell.

The Environment Provider
PowerShell has a feature called providers that creates one or more drives, which are hierarchical, file system-like structures that allow a user to manage various areas in Windows. One of those providers is for environment variables called Environment.

PS C:\> Get-PSProvider -PSProvider Environment

Name                 Capabilities                                                      Drives
----                 ------------                                                      ------
Environment          ShouldProcess                                                     {Env}

As you can see above, the Environment provider has a drive called Env. This drive exposes all environment variables on a Windows system. For example, you can use Get-ChildItem to enumerate all user environment variables on your system.

PS C:\> Get-ChildItem -Path Env:\

Name                           Value
----                           -----
ADPS_LoadDefaultDrive          0
ALLUSERSPROFILE                C:\ProgramData
API_Location_ComputerVision    eastus2
API_SubscriptionKey_Compute... e937bbf5cea841728c64c4eda00e1aca
APPDATA                        C:\Users\Administrator.FUSIONVM\AppData\Roaming
CommonProgramFiles             C:\Program Files\Common Files
CommonProgramFiles(x86)        C:\Program Files (x86)\Common Files
CommonProgramW6432             C:\Program Files\Common Files
<SNIP>

You can then filter this information using common filtering techniques like Where-Object, Select-Object and so on.

We can also set our location directly on the Env drive and then reference environment variables by their name.

PS> Set-Location -Path Env:\
PS> Get-ChildItem -Path COMPUTERNAME

Name                           Value
----                           -----
COMPUTERNAME                   MYCOMPUTER

Using the $env Variable
We can also access environment variables using the built-in variable called $env followed by a colon and the name of the environment variable. For example, instead of using Get-Item or Get-ChildItem and using the Env drive, I can save some keystrokes and instead simply specify $env:COMPUTERNAME.

The $env variable can be used to access all user context environment variables. This option allows you to type $env: followed by the tab key, which cycles through all of the available environment variables.

Changing Environment Variables
Perhaps you need to change an environment variable. A common one to change is the PATH variable. To do this, we can simply define the $env:PATH variable to a different value just as you would a normal variable.

PS Env:\> $env:PATH
C:\Users\Administrator.FUSIONVM\AppData\Local\Programs\Python\Python36\Scripts\;C:\Users\Administrator.FUSIONVM\AppData\Local\Programs\Python\Python36\;C:\Users\Administrator.FUSIONVM\AppData\Local\Microsoft\WindowsApps;C:\Program Files\Microsoft VS Code\bin
PS Env:\> $env:PATH = 'foo'
PS Env:\> $env:PATH
foo

Persistence and .NET
You can see above that it's as simple as that...but this isn't persistent. Once I restart my PowerShell session, my old path will be back. If I need to ensure my new environment variable persists, I'll need to step over to .NET, which opens up a lot of other ways to work with environment variables.

We can also read and set environment variables using PowerShell by using static method on the System.Environment object. This method allows us to not only read user environment variables but system variables, as well.

For example, we can query an environment variable with the GetEnvironmentVariable() method using [System.Environment]::GetEnvironmentVariable('PATH') as an example. Using this method, we can also find system-level environment variables by adding machine as the second argument.

PS> [System.Environment]::GetEnvironmentVariable('PATH','machine')

We've been doing a lot of reading, but we can also write environment variables and ensure they remain persistent across sessions. To do that, we can use the SetEnvironmentVariable() method using the name of the variable, the value and finally the target, which will either be Machine, Process or User.

In the below example, I'm creating a persistent, system-level new environment variable called FOO with the value of bar.

PS> [System.Environment]::SetEnvironmentVariable('FOO', 'bar',[System.EnvironmentVariableTarget]::Machine)

Getting Help
As you can see, environment variables can be managed a few different ways. Your preference and persistence needs will determine how you choose to work with them in your PowerShell scripts.

For a full breakdown on working with environment variables in PowerShell, check out the help section by running Get-Help -Name about_Environment_Variables.

About the Author

Adam Bertram is a 20-year veteran of IT. He's an automation engineer, blogger, consultant, freelance writer, Pluralsight course author and content marketing advisor to multiple technology companies. Adam also founded the popular TechSnips e-learning platform. He mainly focuses on DevOps, system management and automation technologies, as well as various cloud platforms mostly in the Microsoft space. He is a Microsoft Cloud and Datacenter Management MVP who absorbs knowledge from the IT field and explains it in an easy-to-understand fashion. Catch up on Adam's articles at adamtheautomator.com, connect on LinkedIn or follow him on Twitter at @adbertram or the TechSnips Twitter account @techsnips_io.


comments powered by Disqus
Most   Popular