PowerShell and Environment Variables: A Deep Dive

choubertsprojects

The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

PowerShell is a scripting language designed for system administrators, and it’s built on the .NET framework. Environment variables are one of its most powerful features that help you manage your environment as you script away. In this article we’ll learn how to use PowerShell with environment variables in depth, including using them to control access to files and other resources.

The “powershell set environment variables” is a command-line tool that allows users to set environmental variables in PowerShell. It is a useful tool for creating scripts and automating tasks.

PowerShell and Environment Variables: A Deep Dive

Once you know the secret, using PowerShell to set Windows environment variables, read environment variables, and create new environment variables is simple. The tips in this article apply to Windows 10 environment variables as well as any Windows client/server released after Windows 7 SP1/Windows Server 2008.

From $env: PSDrive, the registry, and the [System.Environment].NET class, PowerShell offers a variety of methods to deal with Windows environment variables. This step-by-step overview will teach you about each approach, including how to grasp the scope of environment variables.

Assumptions

I’ll be using Windows PowerShell 5.1 on Windows 10 throughout this post. However, the approaches I’m going to teach you should work properly if you have any version of Windows PowerShell later than v3 on Windows 7 SP1 or later.

What are Environment Variables and How Do They Affect You?

As the name implies, environment variables hold information about the environment that Windows and apps utilize. Graphical apps like Windows Explorer and simple text editors like Notepad, as well as cmd.exe and PowerShell, may access environment variables.

Using environment variables in your PowerShell scripts or modules allows you to avoid hard-coding file locations, user or machine names, and much more.

Variables in the Environment

As you begin to learn more about how to work with environment variables in PowerShell, you’ll come across many different variables. Some are more useful than others. Below is a list of some of the Variables in the Environment and their usage for reference.

Variable Usage
ClientName The name of the distant machine to which a Remote Desktop connection has been established.
SessionName This is useful for determining if the current Windows session is considered to be running at the console by the operating system. SessionName will be ‘Console’ for console sessions. Standard Sessions do not disclose SessionName as ‘Console’, however Enhanced Session connections to Hyper-V Virtual Machines do.
COMPUTERNAME The computer’s name is
Windir and SystemRoot The current Windows installation’s path.
ProgramFiles and ProgramFiles are two different types of program files (x86) For both x64 and x86 applications, these are the default locations.
ProgramW6432 Programs are installed at this place by default, avoiding 32/64 bit redirection. Only 32-bit processes executing on a 64-bit platform are affected by this variable. This implies you can use it to tell whether a 32-bit PowerShell instance is running on a 64-bit machine.
USERDNSDOMAIN The Fully Qualified Domain Name of the Active Directory domain where the current user is currently logged in. This is just for domain logons.
USERDOMAIN The name of the domain to which the current user has signed in in NETBIOS format. If there is no domain, it may be a computer name.
USERDOMAINRoamingProfile If there is one, the location of the user’s central copy of the roaming profile. This is just for domain logons.
UserName The name of the person who is presently logged in.
USERPROFILE On the local computer, the location of the current user’s profile.

Variable Scopes in the Environment

Environment variables are divided into three categories. Consider scopes to be layers of variables that add up to a complete picture. These “layers” work together to deliver a wide range of environment variables to any Windows process.

“Hierarchy” is a variable scope environment.

Each of these “layers” either combine or overwrite one another. They are defined in a hierarchy like: machine –> user –> process with each scoped variable overwriting the parent variable if one exists in the parent scope.

TEMP, for example, is a frequent environment variable. The location to Windows’ local temporary folder is stored in this variable. The value of this environment variable is:

  • In the machine scope, C:WINDOWSTEMP
  • C:Users<username>AppDataLocalTemp in the user scope
  • C:Users<username>AppDataLocalTemp in the process scope.

The ultimate result will be C:WINDOWSTEMP if the TEMP environment variable is not specified in the user scope.

Variable Scope Types in the Environment

There are three different Variable Scopes in the Environment in Windows.

Machine

Environment variables in the machine scope are linked to the current Windows instance. These may be viewed by any user account, but they must be set, changed, or deleted by someone with higher access.

User

The user operating the current process is related with the environment variables in the user scope. Machine-scoped variables with the same name are overwritten by user variables.

Machine and User scoped environment variable values should not exceed 2048 characters, according to Microsoft.

Process

The process scope’s environment variables are a mix of machine and user scope variables, as well as certain dynamically created variables by Windows.

The following is a list of environment variables that a running process may use. All of these variables are generated dynamically.

  • ALLUSERSPROFILE
  • APPDATA
  • COMPUTERNAME
  • HOMEDRIVE
  • HOMEPATH
  • LOCALAPPDATA
  • LOGONSERVER
  • PROMPT
  • PUBLIC
  • SESSION
  • SystemDrive
  • SystemRoot
  • USERDNSDOMAIN
  • USERDOMAIN
  • USERDOMAIN ROAMINGPROFILE
  • USERNAME
  • USERPROFILE

Variables in the Registry that affect the environment

Environment variables are saved in two registry locations: one for user scope and another for machine scope.

If you want to manage environment variables, don’t use the registry.

When it comes to changing variables in the register, there’s a catch. Variable changes in the registry will not be seen by any ongoing processes. Unless Windows tells them that something has changed, processes only view the registry variables and values that were there when the process was launched.

You may use a.NET class instead of simply altering the registry. The [System.Environment] class in.NET may adjust machine and user–scoped environment variables as well as take care of registry maintenance.

Modifying Variables in the Registry that affect the environment directly, whilst possible, doesn’t make sense. The .NET class offers a simpler, Microsoft-supported approach. You’ll learn about Using the.NET Framework’s [System.Environment] Class later in this article.

Variable Registry Locations and Querying in the Environment

I hope I’ve persuaded you not to edit the registry directly, but if you want to peep inside, the HKEY CURRENT USEREnvironment entry contains all user environment variables. HKEY LOCAL MACHINESYSTEM stores machine-scoped environment variables. ManagerEnvironment CurrentControlSetControlSession

Registry values of type REG SZ or REG EXPAND SZ may be found within any of these keys. REG EXPAND SZ values include embedded environment variables in their value. When the value is retrieved, these environment variables are extended.

Use the REG utility to illustrate this. This is a simple command-line tool that comes pre-installed with Windows.

As seen below, query the TEMP environment variable. To get the value of the TEMP variable, use REG with the QUERY argument.

> REG QUERY HKCUEnvironment /V TEMP HKEY_CURRENT_USEREnvironment TEMP REG_EXPAND_SZ %USERPROFILE%AppDataLocalTemp

You’ll see environment variables surrounded by percentage symbols (percent COMPUTERNAME percent) on occasion, as seen above. Using cmd.exe and batch files, this is the old-school method of displaying environment variables. This is a format that PowerShell does not recognize.

We may view the registry value’s native value using the REG utility. REG EXPAND SZ is the value type, and the value includes the percent USERPROFILE environment variable.

If you’d prefer obtain the registry value using PowerShell, use the Get-Item cmdlet, as demonstrated below.

PS51> Get-ItemProperty -Path HKCU:Environment -Name TEMP TEMP : C:Users<your username>AppDataLocalTemp PSPath : Microsoft.PowerShell.CoreRegistry::HKEY_CURRENT_USEREnvironment PSParentPath : Microsoft.PowerShell.CoreRegistry::HKEY_CURRENT_USER PSChildName : Environment PSDrive : HKCU PSProvider : Microsoft.PowerShell.CoreRegistry

Using the GUI, you can see and change Windows Environment Variables.

Run SystemPropertiesAdvanced.exe from PowerShell, a command prompt, or Windows Key+R to open the System Properties Advanced tab and see a GUI representation of the user and system environment variables. The EnvironmentVariables button, which is indicated in the figure below, should be selected.

The Advanced tab of the System Properties dialogThe Advanced tab of the System Properties dialog

You may examine, create, and change user and machine-scoped environment variables in the Environment Variables window (shown below). Machine-scoped variables are referred to as System variables in the dialog.

The Environment Variables window appears.The Environment Variables window appears.

Now that you know what environment variables are, let’s get to the point of this article: manipulating them using PowerShell!

You may use PowerShell to interact with environment variables in a few different ways.

  • PSDrive and Provider — session-based environment Only for the current PowerShell session, sets the values of environment variables.
  • variables – session-based $env Only for the current PowerShell session, sets the values of environment variables.
  • The.NET Class [System.Environment] enables you to save user and system-scoped environment variables across sessions and reboots.

PSDrive and Provider in the Environment

A PowerShell concept known as PowerShell drives is one of the finest ways to read environment variables (PS drives). Through the Env: drive on a PS drive, you may treat environment variables as if they were a file system.

Changing to the Environment: Drive

You refer to it using paths like Env:TEMP, Env:COMPUTERNAME, and so on, just like any other PS drive. Switch to the Env: drive as you would any other file system drive to save some keystrokes, as seen below.

PS51> cd Env: PS51 Env:> ## or PS51> Set-Location Env: PS Env:>

Completion of the Env: Drive tab

To access environment variables, use the same commands you’d use to access a file system, such as Get-Item and Get-ChildItem. You’re reading the Env: drive instead of the file system.

Because environment variables are saved on a PS disk, you may cycle between the accessible variables using PowerShell’s tab completion function, as illustrated below.

Env: tab completion - finding environment variables starting with the letter CEnv: tab completion – identifying variables in the environment that begin with the letter C

Now let’s look at some instances of how you can utilize the Env: PS drive to deal with variables in the environment.

Using Env to List Environment Variables:

PS51> Get-Item -Path Env: PS51> Get-Item -Path Env:USERNAME

Using Env to List Environment Variables with a Wildcard:

PS51> Get-Item -Path Env:user*

Using Env to Find Environment Variable Values:

These instructions return [System.Collections.DictionaryEntry].NET objects with key/value pairs. The Name property of these objects holds the name of the environment variable, while the Value property holds the value.

Wrapping the Get-Item command reference in parentheses and referencing the Value property as shown below allows you to obtain a particular value of an environment variable:

PS51> (Get-Item -Path Env:COMPUTERNAME).Value MYCOMPUTERHOSTNAME

Use conventional PowerShell cmdlets such as Pick-Object and When-Object to select and filter the objects supplied by the Env: provider in cases where you only need to retrieve certain environment variables.

Only the environment variable COMPUTERNAME is returned in the example below.

PS51> Get-ChildItem -Path Env: | Where-Object -Property Name -eq ‘COMPUTERNAME’

Use the Get-Content cmdlet as a backup option. The value of the environment variable is returned by this cmdlet as a [String] object. This object is easier to work with than an object having Name and Value attributes since it simply returns the value.

PS51> Get-Content -Path Env:COMPUTERNAME

Inserting Environment Values into a String (demo)

You may use Get-Content to get the value of an environment variable and put it into a text string, for example, the COMPUTERNAME environment variable.

PS51> ‘Computer Name is: {0}’ -f (Get-Content -Path Env:COMPUTERNAME) Computer Name is: MYCOMPUTER

Setting (and Creating) an Environment Variable using Env:

Create new environment variables with PowerShell using the New-Item cmdlet. Provide the name of the environment variable in the form Env:<EnvVarName> for the Name value and the value of the environment variable for the Value parameter as shown below.

PS51> New-Item -Path Env:MYCOMPUTER -Value MY-WIN10-PC Name Value —- —– MYCOMPUTER MY-WIN10-PC

Set an environment variable using the Set-item cmdlet, or create a new one if one doesn’t exist. You may create or alter an environment variable with the Set-Item cmdlet, as shown below.

PS51> Set-Item -Path Env:testvariable -Value “Alpha”

Using Env to Copy an Environment Variable:

You may find yourself in a position where you need to duplicate the value of an environment variable. The Copy-Item cmdlet may be used to do this.

The value of the COMPUTERNAME variable is transferred to MYCOMPUTER, overwriting its current value, as seen below.

PS51> Get-Item -Path Env:MYCOMPUTER Name Value —- —– MYCOMPUTER MY-WIN10-PC PS51> Copy-Item -Path Env:COMPUTERNAME -Destination Env:MYCOMPUTER PS51> Get-Item -Path Env:MYCOMPUTER Name Value —- —– MYCOMPUTER WIN10-1903

Using Env to Remove an Environment Variable:

There will be times when an environment variable is no longer required. One of three approaches may be used to delete environment variables:

  • Set an environment variable to an empty value using the Set-Item cmdlet.

PS51> Set-Item -Path Env:MYCOMPUTER -Value ”

PS51> Remove-Item -Path Env:MYCOMPUTER

  • Clear an item using the Clear-Item cmdlet.

PS51> Clear-Item -Path Env:MYCOMPUTER

Using Env to rename an Environment Variable:

When the name of an environment variable has to be changed, you may use the Env: provider to rename rather than remove and rebuild the variable.

To alter the name of an environment variable while preserving its value, use the Rename-Item cmdlet. You can see that the MYCOMPUTER variable has been renamed to OLDCOMPUTER while preserving its value in the example below.

PS51> Rename-Item -Path Env:MYCOMPUTER -NewName OLDCOMPUTER PS51> Get-Item -Path OLDCOMPUTER Name Value —- —– OLDCOMPUTER WIN10-1903

Variables in $Env

This part teaches you how to handle environment variables as variables once you’ve mastered the Env: drive to treat them as files. The PowerShell Expression Parser is another approach to handle in-session environment variables. This feature lets you to access environment variables via the $Env: scope.

Using $Env to get an Environment Variable:

You may directly access environment variables using the $Env scope instead of using a command like Get-Item, as illustrated below.

This approach makes it simple to include environment variables in strings such as the following:

PS51> “The Computer Name is {0}” -f $env:COMPUTERNAME The Computer Name is WIN10-1809 PS51> “The Computer Name is $env:COMPUTERNAME” The Computer Name is WIN10-1809

Using $Env to set or create an environment variable:

Using this approach, you can easily set an environment variable. If one does not already exist, a new environment variable will be created, as seen below.

PS51> $env:testvariable = “Alpha”

Rather of overwriting an existing value, use the += syntax to add to it.

PS51> $env:testvariable = “Alpha” PS51> $env:testvariable += “,Beta” PS51> $env:testvariable Alpha,Beta

Using $Env to remove an Environment Variable:

Set the value of an environment variable to an empty string to delete it using this technique.

PS51> $env:testvariable = ”

Using the.NET Framework’s [System.Environment] Class

The [System.Environment].NET class also has methods for accessing and setting environment variables. This is the only way to directly access different environment scopes and define environment variables that are persistent between PowerShell sessions.

If no scope is supplied, the process scope is assumed in all of the following instances.

You’ll utilize a few different.NET static class methods while utilizing [System.Environment]. You don’t need to know what a static method is to use it. To utilize any of the approaches you’re going to learn, you simply need to know how to reference the class ([System.Environment]), followed by two colons (::), and then the method.

Using [System] to List Environment Variables .Environment]

You’d use the GetEnvironmentVariables function to view all environment variables in a certain scope. This function retrieves all environment variables that fall inside the scope given in the method parameter (in parentheses).

PS51> [System.Environment]::GetEnvironmentVariables(‘User’) PS51> [System.Environment]::GetEnvironmentVariables(‘Machine’) PS51> [System.Environment]::GetEnvironmentVariables(‘Process’) # The same as Process PS51> [System.Environment]::GetEnvironmentVariables()

Using [System] to Get Single Environment Variables .Environment]

If you need to locate a certain environment variable, you have two options.

  • GetEnvironmentVariables().<var name> – not recommended
  • GetEnvironmentVariable(‘<var name>’,'<scope>’)

GetEnvironmentVariables()

You utilize dot notation to reference the value when using the GetEnvironmentVariables() function. The [System.Environment] class and static method references should be enclosed in parentheses, followed by a dot, and the name of the environment variable, as seen below:

PS51> ([System.Environment]::GetEnvironmentVariables()).APPDATA

It’s important to note that when referring environment variables in this manner, capitalization must match! Try using appdata to refer to the APPDATA variable in the example above. Instead, use GetEnvironmentVariable().

GetEnvironmentVariable()

To find single environment variables, instead of using GetEnvironmentVariables(), use GetEnvironmentVariable(). It avoids the capitalization problem while also allowing you to select the scope.

To use this technique, provide the name of the environment variable and the scope in which you want to search for it, separated by a comma.

PS51> [System.Environment]::GetEnvironmentVariable(‘COMPUTERNAME’,’User’) # Blank PS51> [System.Environment]::GetEnvironmentVariable(‘COMPUTERNAME’,’Machine’) # Blank PS51> [System.Environment]::GetEnvironmentVariable(‘COMPUTERNAME’,’Process’) WIN10-1903 # The same as Process PS51> [System.Environment]::GetEnvironmentVariable(‘COMPUTERNAME’) WIN10-1903

Using [System] to Set an Environment Variable .Environment]

Set the value of an environment variable for the provided scope, or create a new one if one does not already exist, using the SetEnvironmentVariable() function.

When you put variables in the process scope, you’ll see that modifications to the user and machine scopes are permanent, while the process scope is volatile.

PS51> [System.Environment]::SetEnvironmentVariable(‘TestVariable’,’Alpha’,’User’) PS51> [System.Environment]::SetEnvironmentVariable(‘TestVariable’,’Alpha’,’Process’) PS51> [System.Environment]::SetEnvironmentVariable(‘TestVariable’,’Alpha’,’Machine’) # The same as Process PS51> [System.Environment]::SetEnvironmentVariable(‘TestVariable’,’Alpha’)

An exception will be raised if you use the SetEnvironmentVariable method with a variable name or value of 32767 characters or greater.

Using [System] to remove an environment variable .Environment]

Set the value of an environment variable to an empty string using the SetEnvironmentVariable() function to delete it for the provided scope.

PS51> [System.Environment]::SetEnvironmentVariable(‘TestVariable’, ”, ‘User’) PS51> [System.Environment]::SetEnvironmentVariable(‘TestVariable’, ”, ‘Process’) PS51> [System.Environment]::SetEnvironmentVariable(‘TestVariable’, ”, ‘Machine’) # The same as process PS51> [System.Environment]::SetEnvironmentVariable(‘TestVariable’, ”)

Environment Variables in PowerShell That Are Useful

PowerShell, like many other Windows programs, has its own set of environment variables. PSExecutionPolicyPreference and PSModulePath are two useful environment variables to be aware of.

PSExecutionPolicyPreference

The current PowerShell execution policy is stored in the PSExecutionPolicyPreference environment variable. It is produced if the following PowerShell execution policy is defined for the current session:

  • Using the Set-ExecutionPolicy cmdlet with Process as the Scope argument
  • To start a new session, run the powershell.exe program and use the ExecutionPolicy command line option to define a policy for the session.

PSModulePath

If you don’t supply a complete path, PowerShell looks for modules using the PSModulePath environment variable. Individual directory paths are separated by a semicolon, much like the normal PATH environment variable.

PS51> $env:PSModulePath C:Program FilesWindowsPowerShellModules;C:WINDOWSsystem32WindowsPowerShellv1.0Modules

Quick suggestion: Using $env:PSModulePath.split(‘;’), split each folder to generate a string array to analyze each path independently.

Summary

Environment variables may be used to gather information about a running system or to save data between sessions and reboots. You can now control your environment variables using PowerShell in a number of ways, whether you’re merely reading the usual Windows operating system environment variables or generating your own!

Additional Reading

PowerShell and Environment Variables: A Deep Dive is a blog post that talks about the PowerShell environment variables. It includes a list of all the environment variables, how to read them, and their functions. Reference: powershell environment variables list.

mean in PowerShell?","acceptedAnswer":{"@type":"Answer","text":"Answer3"}}]} is a placeholder for the current command line arguments."}}]} mean in PowerShell?","acceptedAnswer":{"@type":"Answer","text":"A: mean in PowerShell?","acceptedAnswer":{"@type":"Answer","text":"Answer3"}}]} is a placeholder for the current command line arguments."}}]}

Frequently Asked Questions

What does $ENV mean in PowerShell?

A: $ENV is a variable that contains the active environment. It can be used to determine if you are in an elevated PowerShell prompt or not, and also what the current user account name is.

How do I pass an environment variable in PowerShell?

A: There is no built-in command to do this, but you can use the following PowerShell script.

What does $_ mean in PowerShell?

A: $_ is a placeholder for the current command line arguments.

Related Tags

  • powershell print environment variables
  • powershell set environment variable path
  • powershell environment variables
  • powershell remove environment variable permanently
  • [environment]::setenvironmentvariable

Table of Content