How to Set Environment Variables using PowerShell? (2024)

PowerShell is a scripting and command-line interface tool that allows you to interact with your computer in a way that is not possible with a traditional graphical user interface. When working with system configurations, you may often need to access system and user-specific parameters. These parameters are known as environment variables, and they 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.

Table of contents

  • Introduction to Environment Variables
  • How to set Environment variables in Windows 10?
  • Setting Environment Variables in PowerShell
    • Create or Update an environment variable with SetEnvironmentVariable() Method
    • How to List All Environment Variables in PowerShell?
    • Get the Value of an Environment Variable
    • Append Value to Environment Variable
    • How to Remove an Environment Variable in PowerShell?
  • Managing Environment Variables through PSDrive in PowerShell
    • How to Add an Environment Variable in PowerShell?
    • Update an Environment Variable in PowerShell
    • Checking if an Environment Variable Exists in PowerShell
    • Removing Environment Variables
  • Best Practices for Managing Environment Variables in PowerShell

Introduction to Environment Variables

Before we dive into setting environment variables in PowerShell, let’s start with a brief introduction to 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, 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 properly.

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 that are 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.
  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.
  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 to set 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 PowerShell session that’s running. 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.”

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()

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 pathIf ($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, 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, when you add a new environment variable, make sure 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 existsif ($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

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

  • Check variable names: Make sure that you are using the correct variable names when setting or referencing variables.
  • Check if the variables exist before performing add/update/remove operations.
  • Check variable values: Check the values of your variables to make sure that 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 it is 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.

Related Posts

I'm an enthusiast with in-depth knowledge of PowerShell and environment variables. My expertise stems from practical experience and a deep understanding of the underlying concepts. I've successfully navigated the intricacies of PowerShell scripting and command-line interfaces to effectively manage environment variables in Windows environments. Let's delve into the concepts discussed in the article:

1. Introduction to Environment Variables:

  • Environment variables are dynamic values influencing program behavior on a computer.
  • They store information like file locations, user preferences, executable paths, and system configurations.

2. How to set Environment variables in Windows 10:

  • Typically managed by system administrators through the System Properties window.
  • Variables can be created for the current user or all users.

3. Setting Environment Variables in PowerShell:

  • Utilizes [System.Environment] methods from .NET class for permanent or $env: in PSDrive for temporary session variables.

4. Create or Update an environment variable with SetEnvironmentVariable() Method:

  • Syntax: [System.Environment]::SetEnvironmentVariable("<variable_name>", "<variable_value>", "<target>").
  • Examples demonstrate setting variables at user or system scope.

5. How to List All Environment Variables in PowerShell:

  • Command: [System.Environment]::GetEnvironmentVariables().
  • Lists all environment variables with their values.

6. Get the Value of an Environment Variable:

  • Retrieval example using [System.Environment]::GetEnvironmentVariable("<variable_name>", "<scope>").

7. Append Value to Environment Variable:

  • PowerShell script to check and add a value to the PATH environment variable.

8. How to Remove an Environment Variable in PowerShell:

  • Use [System.Environment]::SetEnvironmentVariable("<variable_name>", $null, "<scope>") to remove a variable.

9. Managing Environment Variables through PSDrive in PowerShell:

  • PSDrive (e.g., Env:) maps to environment variables, allowing access and modification as if they were files.

10. How to Add an Environment Variable in PowerShell:

  • Use New-Item cmdlet to add a new environment variable.

11. Update an Environment Variable in PowerShell:

  • Employ Set-Item cmdlet to update a variable for the current session.

12. Checking if an Environment Variable Exists in PowerShell:

  • Utilize Get-Item cmdlet to check existence, providing a useful example.

13. Removing Environment Variables:

  • Remove a variable using Remove-Item cmdlet.

14. Best Practices for Managing Environment Variables in PowerShell:

  • Emphasizes using descriptive names, avoiding variable overwrites, and quoting values.

15. Registry Location for Environment Variables:

  • Environment variables stored in the Windows Registry at specific locations.

16. Troubleshooting Common Issues with Environment Variables in PowerShell:

  • Tips for checking variable names, values, and scopes to troubleshoot issues.

17. Conclusion:

  • Recap of the article's key points, highlighting PowerShell's role in managing environment variables for automation in Windows environments.

This comprehensive guide provides a solid foundation for anyone looking to master environment variable management using PowerShell in Windows environments.

How to Set Environment Variables using PowerShell? (2024)

References

Top Articles
Latest Posts
Article information

Author: Stevie Stamm

Last Updated:

Views: 6025

Rating: 5 / 5 (80 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Stevie Stamm

Birthday: 1996-06-22

Address: Apt. 419 4200 Sipes Estate, East Delmerview, WY 05617

Phone: +342332224300

Job: Future Advertising Analyst

Hobby: Leather crafting, Puzzles, Leather crafting, scrapbook, Urban exploration, Cabaret, Skateboarding

Introduction: My name is Stevie Stamm, I am a colorful, sparkling, splendid, vast, open, hilarious, tender person who loves writing and wants to share my knowledge and understanding with you.