How to Set the Environment Variables in PowerShell?

powershell set environment variable

PowerShell is a scripting and command-line interface tool that allows you to interact with your computer in a way that is impossible with a traditional graphical user interface. You may often need to access system and user-specific parameters when working with system configurations. These parameters are known as environment variables and offer a convenient way to retrieve crucial data and customize your applications and scripts. In this article, I will show you how to set environment variables like a pro in PowerShell.

Introduction to Environment Variables

Before we dive into setting environment variables in PowerShell, let’s briefly introduce environment variables. Environment variables are a set of dynamic values that can affect the behavior of programs running on your computer. They are used for storing information such as the location of system files, system drives, number of processors, user preferences, the path to executable files, the location of Windows Operating system files, user profile path, and other system-specific configurations. Environment variables are essential for many software programs to run correctly.

Here are some examples of common environment variables used:

  • Path: This variable contains a list of directories that Windows searches when looking for executable files.
  • TEMP: This variable contains the path to the temporary folder on your computer.
  • USERNAME: This variable contains the username of the currently logged-in user.
  • PSModulePath: The psmodulepath environment variable contains a list of locations searched to find modules and resources.

How to set Environment variables in Windows 10?

Typically, Environment variables are set, modified, and deleted by system administrators. You can set an environment variable through the System Properties window. Here’s how:

  1. Go to the Start menu, search for “Edit the system environment variables”, and click on the result.
  2. In the “System Properties” window that pops up, click on the “Environment Variables” button at the bottom right.
    Get Environment Variables
  3. This will open the “Environment Variables” window. Here you’ll see two boxes, “User variables” (specific to the current user) and “System variables” (available to all users).
  4. Decide whether you want to create a user or a system variable: To create a user variable, click the “New” button under the “User variables” or the “System variables” box.
    environment variables
  5. In the “New User Variable” or “New System Variable” window that pops up, type the name of the variable in the “Variable name” field and the value of the variable in the “Variable value” field.
  6. Click “OK” to close the dialog box. Then click “OK” again to close the “Environment Variables” window, and once more to close the “System Properties” window.

Remember, any changes you make to the environment variables will only affect new Command Prompt or PowerShell sessions, not any that are currently open. So you’ll need to start a new session to see your changes.

Setting Environment Variables in PowerShell

To manage environment variables from PowerShell, You can use the [System.Environment] methods from .NET class that sets the environment variables permanently or by using the $env: in PSDrive for temporary session variables.

Create or Update an environment variable with SetEnvironmentVariable() Method

To add or update an environment variable, You can use the SetEnvironmentVariable () method. The syntax for adding or updating an environment variable with .Net Framework method “SetEnvironmentVariable” is as below:

[System.Environment]::SetEnvironmentVariable("<variable_name>", "<variable_value>" ,"<target>")

Here is an example of setting an environment variable at user scope:

[System.Environment]::SetEnvironmentVariable("MY_VAR","My_Value","User")

This will set “MY_VAR” to “My_Value” for the current user. If you want the variable to be available for all users, replace ‘User’ with ‘Machine’. You can also use the Process scope that contains environment variables associated with the current process or the running PowerShell session. To set system environment variables, use the scope as “Machine” (System scope).

[System.Environment]::SetEnvironmentVariable("MY_VAR","My_Value",[System.EnvironmentVariableTarget]::Machine)

Make sure you run the PowerShell script as administrator. Otherwise, you’ll get an error: “Exception calling ‘SetEnvironmentVariable’ with ‘3’ argument(s): Requested registry access is not allowed.”. User variables overwrite machine-scoped variables having the same name.

How to List All Environment Variables in PowerShell?

To list all environment variables in PowerShell, you can use the Similarly, with .Net framework, use the following command:

[System.Environment]::GetEnvironmentVariables()
Get Environment Variables in PowerShell

This command will list all environment variables in PowerShell, along with their values.

Get the Value of an Environment Variable

To retrieve the value of a specific environment variable, E.g., “OneDrive” under the “User” section, use the following:

[System.Environment]::GetEnvironmentVariable("OneDrive", "User")

Append Value to Environment Variable

Here is a PowerShell script to check if a particular value exists in the PATH environment variable; add it if not! The values are separated by semicolon.

# Define the path you want to check and add
$PathToCheck = "C:\WINDOWS\System32\WindowsPowerShell\v1.0\"

# Get the current value of the PATH variable
$CurrentPath = [System.Environment]::GetEnvironmentVariable("PATH", "Machine")

# Check if the PATH environment variable contains the path
If ($CurrentPath -notlike "*$PathToCheck*")
{
    # If not, append the path to the PATH environment variable
    $NewPath = $CurrentPath + ";" + $PathToCheck

    #Set the New Path
    [System.Environment]::SetEnvironmentVariable("PATH", $NewPath, "Machine")
    Write-host -f Green "Added '$PathToCheck' to 'Path' Variable!"
}
Else
{
    Write-host -f Yellow "$PathToCheck already exists in 'Path' Variable!"
}

How to Remove an Environment Variable in PowerShell?

To remove an environment variable in PowerShell using the .NET class [System.Environment], use the following script:

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

This removes the “My_Var” from the “User” section of environment variables. The script uses the SetEnvironmentVariable method to set the environment variable’s value to null, effectively removing it. Please note that you must start a new session (open a new PowerShell window) for the changes to take effect.

Managing Environment Variables through PSDrive in PowerShell

In PowerShell, a PSDrive is basically a data store, like a run-time drive, which can map various types of data, such as registry keys, system environment variables, certificate stores, etc. PowerShell comes with a built-in PSDrive called Env: that maps to the environment variables (AKA: PowerShell environment provider). This allows you to access and modify environment variables as if they were files in a drive.

Please note, Adding/Updating/Removing environment variables through PSDrive applies only to the current session and doesn’t affect the user or system environment variables in your computer!

How to Add an Environment Variable in PowerShell?

To add an environment variable in PowerShell, you can use the New-Item cmdlet. For example, to add a new environment variable called NEW_VAR with the value new value, you can use the following command:

New-Item -Path Env:MY_VAR -Value "new value"

One thing to note here is that when you add a new environment variable, ensure it doesn’t conflict with the existing permanent variables. Otherwise, You’ll see “New-Item : The item at path ‘Variable’ already exists.” error.

Update an Environment Variable in PowerShell

To update an environment variable for a PowerShell session, you can use the Set-Item cmdlet with the -Path parameter set to the Env: PowerShell drive and the name and value of the variable. Here’s an example:

Set-Item -Path Env:MyVariable -Value "MyValue"

Checking if an Environment Variable Exists in PowerShell

To check if an environment variable exists in PowerShell, you can use the Get-Item cmdlet with the -Path parameter set to the Env: PowerShell drive and the name of the variable. Here’s an example:

# Define the name of the environment variable
$variableName = "MY_VAR"

# Try to get the environment variable
$EnvVar = Get-Item "Env:$variableName" -ErrorAction SilentlyContinue

# Check if the environment variable exists
if ($EnvVar) {
    Write-host -f Green "Environment variable $variableName exists."
} else {
    Write-host -f Yellow "Environment variable $variableName does not exist."
}

This script will check and return if the MyVariable environment variable exists or not.

Getting Environment Variables in PowerShell Scripts

To get all environment variables: Get-Item cmdlet with the -Path parameter set to the Env: PowerShell drive. The Env: drive is a special drive in PowerShell that provides access to the system’s environment variables (Including the temporary variables from the session and persistent variables). Here’s an example of how to use environment variables in a PowerShell script:

Get-Item -Path Env:

This command gets all the environment variables! You can also use “Dir Env:” or “Get-ChildItem Env:” for the same. Similarly, to view the value of a specific environment variable in PowerShell, you can use the following script:

Get-Item Env:My_Var

Removing Environment Variables

To remove an environment variable in PowerShell, you can use the Remove-Item cmdlet. For example, to remove the MY_VAR environment variable, you can use the following command:

Remove-Item -Path Env:MY_VAR

Append to Environment Value

Let’s append a new value to the environment variable using $Env:App_Path.

# Get the current value of the environment variable
$CurrentValue = (Get-Item 'Env:App_Path').Value

# Define the value you want to append
$ValueToAppend = ";C:\Program Files\MyApp"

# Append the new value to the current value
$NewValue = $CurrentValue + $ValueToAppend

# Set the new value as the environment variable's value
$Env:App_Path = $NewValue

Please remember: To make permanent changes to environment variables (that persist after the session ends), you need to use the .NET class [System.Environment]

Registry Location for Environment Variables

Environment variables are stored in the Windows Registry in the following locations:

  • System-wide environment variables: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]
  • User-specific environment variables: [HKEY_CURRENT_USER\Environment]

Best Practices for Managing Environment Variables in PowerShell

Managing environment variables in PowerShell can be a powerful tool, but it’s important to follow some best practices to avoid common pitfalls. Here are some tips to keep in mind:

  • Use descriptive variable names: Use descriptive variable names that are easy to remember and understand. This will make it easier to maintain your scripts over time.
  • Avoid overwriting existing variables: Be careful when setting variables to avoid overwriting existing variables. This can cause unexpected behavior in your scripts.
  • Use quotes around variable values: Always use quotes around variable values to avoid issues with spaces or special characters.

Troubleshooting Common Issues with Environment Variables in PowerShell

You may encounter some common issues when working with environment variables in PowerShell. Here are some tips to help you troubleshoot these issues:

  • Check variable names: Ensure you use the correct names when setting or referencing variables.
  • Check if the variables exist before performing add/update/remove operations.
  • Check variable values: Check your variables’ values to ensure they are set correctly.
  • Check environment variable scope: Environment variables can have different scopes, so make sure that you are setting and referencing variables in the correct scope.

Conclusion

In this article, we’ve covered the basics of setting and managing environment variables in PowerShell. Whether viewing, creating, modifying, or removing environment variables, PowerShell has you covered. PowerShell offers a quick and easy way to manage environment variables in your Windows environment. Using these powerful scripts, you can automate the management of environment variables in your Windows environment and make your life a lot easier.

What are environment variables in PowerShell?

Environment variables are named data containers that store persistent information used by programs and the operating system. They act like global variables accessible by various applications throughout a session.

How do I get the path environment variable in PowerShell?

To access a specific environment variable in PowerShell, use the $env: prefix followed by the name of the variable. For example, to access the PATH environment variable, you can use $env:PATH.

How do I add environment variables to the path in PowerShell?

Use the Set-Item cmdlet to modify the value of an existing env variable. For example: Set-Item -Path env:PATH -Value "$env:PATH;C:\New\Bin\"
This will add C:\New\Bin\ to the existing PATH variable’s value.

How to set a system environment variable in Windows using PowerShell?

To set a system-wide environment variable, you would use [System.Environment]::SetEnvironmentVariable(‘TEST’, ‘MyValue’, [System.EnvironmentVariableTarget]::Machine). Remember, modifying system-wide environment variables requires administrative privileges.

How do I create a new environment variable in PowerShell?

Use the New-Item cmdlet to create a new env variable. For example: New-Item -Path env:MY_NEW_VAR -Value "variable value". This will create a new environment variable called MY_NEW_VAR with “variable value.”

How can I delete an environment variable?

To remove an environment variable within the current PowerShell session, simply set it to $null using the $env: prefix. For example, $env:TEST = $null. To remove an environment variable persistently, use the [System.Environment]::SetEnvironmentVariable method with a null value: [System.Environment]::SetEnvironmentVariable(‘TEST’, $null, [System.EnvironmentVariableTarget]::Machine).

How do I list all the environment variables?

To view all environment variables in PowerShell, you can use the Get-ChildItem cmdlet on the Env: drive like this: “Get-ChildItem Env:”. This command lists all environment variables available in your session.

How do I use an environment variable in PowerShell scripts?

Use the $env: prefix followed by the variable name. For example, $env:PATH shows the system path variable.

Are there any built-in environment variables in PowerShell?

Yes, PowerShell includes several built-in environment variables that provide information about the system and the user. Some common built-in environment variables include “Path,” “Temp,” “HomePath,” “ComputerName,” and “UserName.” These variables can be accessed and utilized within PowerShell scripts and commands.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

One thought on “How to Set the Environment Variables in PowerShell?

  • EXCELLENT, Thank You

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *