fbpx

PowerShell Environment Variables Tutorial

PowerShell provides a convenient way to manage system and user-specific settings through environment variables. These variables allow for easy configuration of various system parameters and can be accessed and manipulated within PowerShell scripts.

In this article, we will explore the basics of PowerShell environment variables, including how to set, get, and remove them, as well as best practices for using them in your scripts.

What does an Environment Variable do?

An environment variable is a named value that can affect the way running processes behave on a computer. These variables are stored in the operating system’s environment and can be accessed by any program or script that runs on the computer.

Environment variables can be used to store various types of system or user-specific information, such as paths to important files or directories, default program settings, and temporary data.

By using environment variables, programs can be designed to be more flexible and portable, as they can rely on the existence of certain variables without hardcoding specific values.

In PowerShell, environment variables can be used to configure various aspects of the system and to help automate tasks.

Simple PowerShell Environment Variables

Environment variables are a crucial aspect of system configuration and management.

In PowerShell, there are various built-in environment variables that provide valuable information about the operating system, user, and system configuration.

These variables are used by many applications and scripts, making them an essential tool for system administrators and developers.

Some of the common environment variables available in PowerShell include:

  1. USERPROFILE: This variable points to the current user’s profile directory, where user-specific files and settings are stored.
  2. TEMP and TMP: These variables point to the directory where temporary files are stored. Many applications use these directories to write temporary files.
  3. PATH: This variable contains a list of directories separated by semicolons. These directories contain executable files that can be executed from the command line without specifying the full path.
  4. COMPUTERNAME: This variable contains the name of the computer where the script is running.
  5. USERNAME: This variable contains the name of the current user who is running the script

Environment Variable Scopes

Environment variables in PowerShell have a hierarchical scope. This means that variables can have different values depending on the level of the scope they are defined in. The levels of scope, in order of precedence, are:

Process

This is the default scope for environment variables. Process-scoped environment variables are available only to the current PowerShell process and any child processes that it creates. These variables are not visible to other processes or sessions.

User

User-scoped environment variables are available to the current user account and any processes that are run by that user. These variables are not visible to other users on the same computer.

System

System-scoped environment variables are available to all users on the computer. They are set at the system level and are available to all processes and applications on the computer. These variables are typically used to define system-wide settings or paths.

When a variable is called, PowerShell checks the hierarchy from top to bottom to find the first matching definition of the variable.

If a variable is defined at a higher level of the hierarchy, it will override any lower-level definitions of the same variable name. This allows for flexibility in managing and using environment variables in PowerShell.

Registry and Environment Variables 

Managing Environment Variables

It is not recommended to use the registry to manage environment variables in PowerShell. While it is possible to modify environment variables through the registry, it can be a complex and error-prone process.

Additionally, using the registry can lead to inconsistent behavior across different versions of Windows.

Instead, it is recommended to use PowerShell cmdlets and tools to manage environment variables. This ensures that modifications are made in a consistent and reliable manner, and also simplifies the process for users.

 Registry Locations of Environment Variables

In Windows, environment variables can be stored and retrieved from the system registry. There are two main registry locations where environment variables are stored:

  1. User Environment Variables: These are specific to a particular user and are stored in the registry under HKEY_CURRENT_USER\Environment.
  2. System Environment Variables: These variables are available to all users on the system and are stored in the registry under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment.

To view the list of environment variables stored in the registry, you can use the Registry Editor (regedit.exe). Navigate to one of the registry locations mentioned above and you should see a list of environment variables and their values.

Note: Modifying environment variables through the Registry Editor can be risky and is not recommended.

Using the GUI to manage Windows Environment Variables

The GUI method can be useful for those who prefer a visual interface or are less familiar with the command-line options for managing environment variables. However, it is worth noting that using PowerShell or the command prompt can be quicker and more efficient for making bulk changes to environment variables.

PSDrive and Provider

Transferring to the Env: Drive

To switch to the Env: drive, you simply need to type Set-Location Env: or cd Env: in the PowerShell console. Once you are in the Env: drive, you can use the standard PowerShell commands to navigate and manage environment variables. For example, to list all environment variables, you can use the command Get-ChildItem.

Here’s an example of switching to the Env: drive in PowerShell:

PS C:\> cd Env: PS Env:\> dir

This will change the current location to the Env: drive and list all the environment variables available.

Tab-Completion and the Env: Drive

The Env: drive in PowerShell allows for convenient management of environment variables within scripts or the console. In addition to the various methods of managing environment variables, the Env: drive also provides tab-completion support to quickly access and modify variables.

Let’s say you want to quickly check the value of the “TEMP” environment variable. Instead of typing out the full path “Get-ChildItem Env:\TEMP“, you can simply type “ls env:\te” and hit the Tab key to auto-complete the command to “ls env:\TEMP“. This can save you a few keystrokes and make your PowerShell experience more efficient.

Cataloguing Environment Variables with Env:

In PowerShell, the Env: drive provides a way to access and manage environment variables. To list all environment variables using the Env: drive, you can use the Get-ChildItem cmdlet with the Env: drive as the path.

Here’s an example:

Get-ChildItem Env:

This will list all the environment variables and their values in the current console window. You can also use this command to retrieve the value of a specific environment variable by specifying its name as the argument:

Wildcard Cataloguiing Environment Variables with Env:

In PowerShell, you can use the Env: drive to work with environment variables as if they were a file system. This means that you can use various techniques for working with files and directories, such as tab completion and wildcard expansion, to work with environment variables.

One way to use wildcards with the Env: drive is to use the Get-ChildItem cmdlet. For example, to list all environment variables that start with “TEMP”, you can use the following command:

Get-ChildItem Env:TEMP*

This will return a list of environment variables that start with “TEMP”, along with their values.

You can also use the -Filter parameter to specify a wildcard filter. For example, to list all environment variables that contain the word “PATH”, you can use the following command:

Get-ChildItem Env: -Filter *PATH*

This will return a list of all environment variables that contain the word “PATH”, along with their values.

Detecting Environment Variable Values with Env

In PowerShell, you can use the Env: drive to interact with environment variables. One of its useful features is the ability to quickly detect the values of environment variables. To do this, you can use the Get-ChildItem cmdlet with the Env: drive:

Get-ChildItem Env:

This will display a list of all environment variables and their corresponding values. If you want to filter this list to display only certain environment variables, you can use the Where-Object cmdlet:

Get-ChildItem Env: | Where-Object { $_.Name -like "Path" }

In this example, the Where-Object cmdlet is used to filter the list to only display environment variables with the name “Path. You can replace “Path” with any other environment variable name to display its value.

You can also access the value of a specific environment variable directly by referencing it with the Env: drive. For example, to get the value of the “Path” environment variable, you can use:

$env:Path

This will display the value of the “Path” environment variable. You can replace “Path” with any other environment variable name to access its value.

Adding Environment Values to a String

Adding environment variable values to a string can be useful for dynamically creating file paths or for setting configuration values in a script. In PowerShell, you can use the syntax $env:VariableName to access the value of an environment variable.

To add an environment variable value to a string, you can use string interpolation or string concatenation. Here is an example using string interpolation:

$envVar = "USERPROFILE" $path = "$env:$envVar\Documents\example.txt"

In this example, the $envVar variable contains the name of the environment variable we want to access (USERPROFILE). We then use string interpolation to insert the value of the environment variable into the $path variable. The resulting value of $path would be something like C:\Users\Username\Documents\example.txt.

Making an Environment Variable

To create a new environment variable in PowerShell, you can use the New-Item cmdlet. The syntax for creating a new environment variable is:

New-Item -Path Env:<variable_name> -Value <variable_value>

Copying an Environment Variable

To copy an environment variable in PowerShell, you can simply assign the value of the original variable to a new variable:

$originalVariable = "Original Value" $newVariable = $originalVariable

This will create a new variable with the same value as the original. Any changes made to the new variable will not affect the original variable, as they are now two separate variables.

Deleting an Environment Variable

In PowerShell, you can delete an environment variable using the Remove-Item cmdlet with the -LiteralPath parameter to specify the variable you want to delete.

Here is an example that shows how to delete an environment variable named MY_VAR:

Remove-Item -LiteralPath "Env:MY_VAR"

This command will remove the MY_VAR environment variable from the current user’s environment variables. Note that if you want to delete a system environment variable, you need to run the command as an administrator.

Renaming an Environment Variable

To rename an environment variable in PowerShell, you can use the Rename-Item cmdlet to rename the corresponding registry key.

Here is an example:

Rename-Item -Path "HKCU:\Environment\OldVariableName" -NewName "NewVariableName"

This renames the environment variable “OldVariableName” to “NewVariableName” by renaming the corresponding registry key located at HKCU:\Environment\OldVariableName.

$Env: Variables

Acquiring an Environment Variable

Using the $Env: variable prefix in PowerShell allows you to retrieve the value of a specific environment variable. You can simply append the name of the environment variable to $Env: to retrieve its value.

This is a quick and easy way to access environment variables without having to use the Get-ChildItem Env: or Get-Item Env: cmdlets.

Here’s an example of how you can use $Env: to get the value of the TEMP environment variable:

$env:TEMP

This will return the path to the temporary folder on your system.

Making an Environment Variable

To set or create an environment variable using $Env:, you can simply assign a value to the variable using the format $Env:VariableName = “Value”. If the environment variable already exists, its value will be updated with the new value. If it doesn’t exist, a new environment variable will be created with the specified value.

Here’s an example of setting the MyVariable environment variable to a value of 12345:

$Env:MyVariable = "12345"

You can then use the variable in the same PowerShell session, or in any child processes launched from that session.

Deleting an Environment Variable

Deleting an environment variable in PowerShell can be done using the Remove-Item cmdlet with the Env: provider. To delete an environment variable, you need to specify the name of the variable using the syntax:

Remove-Item -Path "Env:<variable_name>"

For example, to delete the “TEMP” environment variable, you would use:

Remove-Item -Path "Env:TEMP"

Note that deleting an environment variable permanently removes it from the system, and any applications that rely on that variable will no longer have access to it.

The [System.Environment] .NET Class

Getting Environment Variables

In addition to using PowerShell’s built-in $Env: drive and cmdlets like Get-ChildItem Env:, you can also use the .NET Framework’s Environment class to work with environment variables in PowerShell.

The Environment class provides various static methods to interact with environment variables, such as GetEnvironmentVariable(), SetEnvironmentVariable(), and RemoveEnvironmentVariable(). These methods can be used to retrieve, set, or delete environment variables in the current process.

To get the value of an environment variable using the Environment class, you can call the static method GetEnvironmentVariable() and pass the name of the variable as a parameter. Here’s an example:

$varValue = [Environment]::GetEnvironmentVariable("MyVar")

Using [System.Environment] to get Single Environment Variables 

In PowerShell, you can use the [System.Environment] class to retrieve a single environment variable. You can do this by calling the GetEnvironmentVariable method and passing the name of the environment variable you want to retrieve as a parameter. Here’s an example:

$varValue = [System.Environment]::GetEnvironmentVariable("MY_VARIABLE")

This will retrieve the value of the environment variable named “MY_VARIABLE” and store it in the $varValue variable. If the specified environment variable does not exist, this method will return $null.

GetEnvironmentVariables()

The GetEnvironmentVariables() method can be used to retrieve all environment variables as a dictionary object. However, it can also be used to retrieve a single environment variable by specifying its name as a parameter.

To retrieve a single environment variable using GetEnvironmentVariables(), you can use the following code:

$varName = "MY_VAR" $varValue = [System.Environment]::GetEnvironmentVariables()["$varName"] Write-Host "The value of $varName is: $varValue"

GetEnvironmentVariable()

In PowerShell, you can use the GetEnvironmentVariable() method to retrieve the value of a single environment variable. This method takes the name of the environment variable as an argument and returns its value. If the environment variable does not exist, it returns $null.

Here’s an example of how to use GetEnvironmentVariable() to get the value of the TEMP environment variable:

$tempPath = [System.Environment]::GetEnvironmentVariable("TEMP") Write-Host "The value of the TEMP environment variable is: $tempPath"

Making an Environment Variable

To set an environment variable using the [System.Environment] class in PowerShell, you can use the SetEnvironmentVariable method. This method takes two parameters: the name of the variable, and its value.

Here’s an example:

[System.Environment]::SetEnvironmentVariable("MY_VARIABLE", "my value")

This will set the environment variable MY_VARIABLE to the value “my value”. If the environment variable already exists, its value will be overwritten. If it doesn’t exist, a new environment variable will be created.

Deleting an Environment Variable

In PowerShell, you can delete an environment variable using the [System.Environment] class by calling the SetEnvironmentVariable() method with a null value for the value parameter. Here is an example:

[System.Environment]::SetEnvironmentVariable("MY_VARIABLE", $null, "User")

In this example, we are deleting the MY_VARIABLE environment variable for the current user. The User argument specifies the scope of the variable to be deleted.

Other Environment Variables

PSExecutionPolicyPreference

The PSExecutionPolicyPreference is an environment variable in PowerShell that determines the execution policy for scripts. This variable can be used to set the default execution policy for the current session or for a specific script.

The available values for the PSExecutionPolicyPreference variable are: “Undefined”, “Restricted”, “AllSigned”, “RemoteSigned”, “Unrestricted”, “Bypass”, “ByPass”, “Undefined”, and “Default”.

By default, the value of the variable is “Undefined”, which means that the execution policy is determined by the policy set in the local group policy. The PSExecutionPolicyPreference variable can be set using the Set-Variable cmdlet or by directly assigning a value to the variable.

PSModulePath

PSModulePath is an environment variable used by PowerShell to store the locations where it searches for modules when they are loaded. Modules in PowerShell are collections of functions, variables, and other resources that can be loaded into a PowerShell session to extend its functionality.

By default, PSModulePath includes several directories that are searched for modules, such as the user’s “Documents\WindowsPowerShell\Modules” folder and the system’s “Program Files\WindowsPowerShell\Modules” folder. 

By now, you should be able to understand what an environment variable on PowerShell is and what it can be used for. If you have further queries, you can visit the Microsoft PowerShell webpage for more details.