Как удалить переменную окружения в windows

Environment variables are special settings that store information about the system and the programs installed on it. They can be used to customize the behavior of applications, scripts, and commands. But can environment variables be deleted? The answer is yes, and that’s a good thing, as sometimes, you may need to modify or remove an environment variable. For example, to change a configuration option or to fix a problem. In this article, I’ll show you how to edit or delete environment variables, as well as how to unset environment variables in Windows using different methods and tools, including Command Prompt and PowerShell.

NOTE: The instructions in this guide apply to both Windows 11 and Windows 10, as everything related to handling environment variables is the same in both operating systems.

Open the Environment Variables window

To make many of the edits shown in this article, you first need to open the Environment Variables window. This guide explains how to do that and shows you the basics about working with environment variables: What are environment variables in Windows?.

The Environment Variables window in Windows

The Environment Variables window in Windows

If you want to skip reading it, one path that works the same in Windows 11 and Windows 10 is to open the Run window (Win + R) and execute the command:

rundll32.exe sysdm.cpl,EditEnvironmentVariables

How to open the Environment Variables in Windows

How to open the Environment Variables in Windows

TIP: You can run the command in Command Prompt, PowerShell, or Windows Terminal to the same end, too.

How to edit an environment variable in Windows

If you want to change the value of an existing environment variable, first select it in the Environment Variables window. Then, click or tap Edit.

How to edit an environment variable in Windows

How to edit an environment variable in Windows

You are shown a window where you can edit both the name and the value of the variable. Make the modifications you want and press OK. Then, press OK one more time in the Environment Variables window.

Editing an environment variable

Editing an environment variable

How to edit an environment variable from Command Prompt

You can create a new environment variable or edit the value of an existing environment variable (but not its name) from the Command Prompt too. If you want to create a user environment variable, enter this command:

setx variable_name “value”

If you want to create a system environment variable, add the m argument to the command like this:

setx variable_name “value” /m

For example, I wanted to create a user variable named TEST with the value C:\digitalcitizen. To that end, I had to run this command:

setx TEST “C:\digitalcitizen”

How to set an environment variable using Command Prompt

How to set an environment variable using Command Prompt

To change the value of an environment variable, run the same setx command but specify a new value for the variable. For instance, to change the value of my TEST environment variable to C:\DC, I have to execute this command:

setx TEST “C:\DC”

How to change the value of an environment variable in Command Prompt

How to change the value of an environment variable in Command Prompt

That works because the setx command rewrites the existing value with the last one you type. Therefore, if you use this command multiple times on the same variable, the variable will keep the last value you typed.

If you want a variable to have multiple paths in its value, you must specify them all in a single setx command, like in the next screenshot. Make sure that each value you enter is separated from the previous one by a semicolon, without spaces.

Add multiple values to an environment variable using CMD

Add multiple values to an environment variable using CMD

TIP: You can get a list of all the environment variables available by running the command:

set

Note that the command is set, not setx, and there aren’t any parameters added to it. Moreover, if you just created or edited an environment variable, you must close and reopen Command Prompt for the changes to show up.

How to see all the environment variables in Command Prompt

How to see all the environment variables in Command Prompt

How to edit an environment variable from PowerShell

You can also create or edit the value of an existing environment variable from PowerShell. If you want to create a user environment variable, the PowerShell command is:

[Environment]::SetEnvironmentVariable(«variable_name»,»variable_value»,»User»)

If you want to create a system environment variable, the command is this one:

[Environment]::SetEnvironmentVariable(«variable_name»,»variable_value»,»Machine»)

For instance, in order to create a user environment variable called TEST with the value digitalcitizen.life, I ran the command:

[Environment]::SetEnvironmentVariable(«TEST»,»digitalcitizen.life»,»User»)

To change the value of the variable later, you can run the same command using a different value. Just like setx in Command Prompt, this command rewrites the value of the specified variable each time you run it.

How to set an environment variable with PowerShell

How to set an environment variable with PowerShell

If you want to assign multiple values to a variable, type all of them in the command, with semicolons between each value, as illustrated below.

How to add multiple values to an environment variable in PowerShell

How to add multiple values to an environment variable in PowerShell

TIP: In PowerShell, you can get a list of all the environment variables by running the command:

Get-ChildItem Env:

However, if you just created or edited an environment variable, you must close and reopen PowerShell for the changes to show up.

How to see all the environment variables in PowerShell

How to see all the environment variables in PowerShell

How to clear the value of an environment variable in Windows (from Command Prompt)

If you want to remove the value of an environment variable (while keeping its name), you can’t do it with the mouse and keyboard from the Environment Variables window. If you select a variable and press Edit, you can delete the value, but you cannot press OK, as this button gets grayed out. Therefore, you can’t save your changes.

Attempt to clear an environment variable in Windows

Attempt to clear an environment variable in Windows

However, you can clear the value of an environment variable using Command Prompt. To unset an environment variable from Command Prompt, type the command:

setx variable_name “”

For example, because I wanted to unset my TEST variable and give it an empty value, I ran this command:

setx TEST “”

How to clear an environment variable with Command Prompt

How to clear an environment variable with Command Prompt

Next, let’s see how to remove an environment variable.

How to delete an environment variable in Windows

If you no longer want to use a particular environment variable, select it in the Environment Variables window. Then, press Delete. Windows does not ask for any confirmation of this action.

How to delete an environment variable in Windows

How to delete an environment variable in Windows

Therefore, if you’ve changed your mind, you must press Cancel to NOT apply the removal. If you want to proceed with the deletion, press OK.

Press OK to delete the variable, or Cancel to keep it

Press OK to delete the variable, or Cancel to keep it

How to use Command Prompt (CMD) to delete an environment variable

To delete an environment variable from Command Prompt, run this command:

REG delete “HKCU\Environment” /F /V “variable_name”

… if it’s a user environment variable, or run this command if it’s a system environment variable:

REG delete “HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment” /F /V “variable_name”

For example, to remove my TEST environment variable from my user’s profile, I ran:

REG delete “HKCU\Environment” /F /V “TEST”

How to unset an environment variable in Windows using Command Prompt

How to unset an environment variable in Windows using Command Prompt

How to use PowerShell to delete an environment variable

To unset and remove an environment variable with PowerShell, type the command:

[Environment]::SetEnvironmentVariable(«variable_name», $null, «User»)

…if it’s a user profile variable, or run this command if it’s a system-wide variable:

[Environment]::SetEnvironmentVariable(«variable_name», $null, «Machine»)

For example, to have PowerShell remove my TEST environment variable from my user profile, I had to run this command:

[Environment]::SetEnvironmentVariable(«TEST», $null, «User»)

How to delete an environment variable from PowerShell

How to delete an environment variable from PowerShell

That’s it!

Why did you need to edit or delete environment variables in Windows?

You now know that Windows can unset environment variables. You’ve seen how to use PowerShell to delete environment variable values and how to use PowerShell to remove environment variables completely. Moreover, you also know how to use CMD to delete any environment variable. But why did you want to change or edit environment variables? Was it because there were leftover variables on your system from certain apps that you no longer used? Or was it because you have a special setup and you need to work with environment variables? Let me know in the comments section below.

In this article, we are going to see how to set, edit and delete environment variables in Windows 11 operating system along with step by step guide with the help of appropriate screenshots. Different-2 programs require different environment variable settings to be executed.
The environment is mainly used to store the information about the system environment running in the current machine.

Basically, The meaning of setting the environment variable is creating a shortcut to start a program instead of remembering the location of the program. By creating the environment you can start the program just by typing a single keyword.
That’s why it is one of the most important for windows users to know how to set environment variables in windows 11.

Headings of Contents

  • 1 What is Environment Variable in Windows?
  • 2 Why You Need to Environment Variable
  • 3 How to Set Environment Variables in Windows 11?
  • 4 How to Change the Environment Variable in Windows 11
  • 5 How to Delete Environment Variable in windows 11
  • 6 How to Set Environment Variable using Command Prompt
  • 7 Changing environment variable using command prompt
  • 8 Access Environment Variable using Command Prompt
  • 9 Setting Environment Variable using Windows Powershell
  • 10 How to Access Environment Variable using Powershell
  • 11 Changing Environment Variable using Windows PowerShell
  • 12 Deleting Environment Variable using Windows Powershell
  • 13 Conclusion

What is Environment Variable in Windows?

The environment variable is the process of setting the dynamic variable value in the machine. In other words, the Environment variable is the way to store the global variable value that is used by all the processes and users that are running under the machine. Environment variables represent the new software installation directory location, Windows Operating system file location, etc. The value of the environment variable is used by the programs to determine where the files are stored actually.

These are some common environment variables available in the windows operating system.

  • Path:- Path is one of the most popular environment variables in the windows operating system that is used to store the list of directories to search for executable programs and also it is one of the most frequently used environment variables.
  • Username:- This is for the username of the system.
  • OS:- The operating system name.

There are other environment variables available except all of the above.

Why You Need to Environment Variable

Windows Environment variables are used to store the data that are used by windows and other programs. For example, windir environment variable stores the location of the Windows installation directory. Programs can query the value of this variable to find where the files of the Windows operating system are located.

There are two types of environment variables available in windows machines first are system variables and the second is user variables that are logged in. Logged-in users can only change their own environment variable if they don’t have administration permission even another user can not change the environment variable.

Let’s take another example about environment variable so that you can get more clarity, Suppose you are going to install Python on your machine and then during the installation of the Python it will ask you, to add a python executable file to your environment variable if you do not check that setting and continue the installation. After successfully the installation of Python you are ready to execute any Python script but you have to remember one thing each time you have to specify the location of the Python executable to execute the Python script but if you check that setting during the installation then you don’t need to specify the location of the Python executable each time.

But after the installation of Python or any software you can manually set the environment variable.

Let’s see how can you set a new environment variable in your windows 11 machine.

Note:- All the variable names which I will set, edit and delete throughout this article will just be for testing. You can set your own required environment variable.

How to Set Environment Variables in Windows 11?

With the help of the following points you can set your environment variable in your windows machine.Here I will go with windows 11 machine.

  • To set the environment variable in Windows you have to right-click on This PC icon and again click on Properties.
  • Now you have to click on “Advanced system settings“.

  • Click on “Environment Variables“.
  • After clicking on Environment variables, you can see all your system environment variables ( User and System ) very clearly.
    1. User Variables:- User variable will contain environment variables about the current logged-in user, If you want to change the environment variable of the logged-in user then you have to change it inside this variables section.
    2. System Variables:- System variable contains variables and values system-wide.This variable will be available for all the users across the machine which means it is a system-wide change.

You can choose according to your need. Here I am going with User variables.

  • After deciding your appropriate environment variables section, click on New.
  • Now, It will ask you to provide the variable name and value of the variable. Here I am setting the Java executable environment variable and after that click OK until all the open environment variables windows are gone.

So finally we have seen the whole process to set new environment variables in the windows 11 machine.

How to Change the Environment Variable in Windows 11

Here I’m gonna show you, how you can change or edit the environment variable.

  • To change the environment variable, press “Windows + R” and type “sysdm.cpl” and hit enter.
  • Go to Advanced > Environment variables section
  • Select the environment variable which you want to change and click edit
  • Provide variable name and variable value as your wish and then click Ok

How to Delete Environment Variable in windows 11

Sometimes you require to delete existing environment variables. With the help of these steps, you can delete any existing environment variables.

  • To delete the environment variable, press “Windows + R” and type “sysdm.cpl” and hit enter.
  • Go to Advanced > Environment variables section.
  • Select the environment variable which you want to delete and click delete.
  • After clicking on delete, your environment variables will be deleted successfully.

How to Set Environment Variable using Command Prompt

Windows command prompt also provides us with some useful commands to work with windows environment variables. here I am going to show how to set environment variables using a command prompt.

  • First, you need to open your command prompt, To open the command prompt press “Windows + R” and type “cmd“, and hit enter.
  • Windows provide a useful command “set” to set the environment variable. The syntax for setting the new environment variable is that set variable_name=variable_value. Here I am going to set an environment variable website=Proogramming Funda so my whole command would be set website=Proogramming Funda.

To verify whether the environment variable was created or not, you can execute the set command. This command shows all the environment variables with values.

Changing environment variable using command prompt

To change the existing environment variable, you have re-assign the value of the existing environment variable by using the following command.

set variable_name=variable_value

Note:- Make sure you are not going to change the variable name.

Access Environment Variable using Command Prompt

To access the existing environment variable in the windows machine, Open the command prompt and issue the set variable_name statement.
Here variable_name represents the name of the variable which you want to access.

As you can see from below the screenshot, I am accessing the website environment variable.

Setting Environment Variable using Windows Powershell

Here I’m gonna show you can set, edit and delete the environment variable using Windows PowerShell.

  • To open Powershell, Press “Windows + R” type “PowerShell” and hit enter.
  • The following is the syntax of the setting new environment variable in windows with help of the windows PowerShell.
$Env:<variable-name> = value

In the above syntax, variable-name represents the name of the variable which you want to keep, and the value represents the value of a variable.

So here I am going to set a variable name website along with the value “Programming Funda“.

How to Access Environment Variable using Powershell

  • To access the existing environment variable using Windows Powershell, Search “Powershell” in the search bar and open windows power shell.
  • The syntax for accessing the environment variable is “$Env:variable_name“. Here I am going to see the value of an environment variable named website.

Changing Environment Variable using Windows PowerShell

If you want to change the value of the existing environment variable using windows PowerShell, Then you have to re-assign the value of the environment variable. As you can see below the image.

Deleting Environment Variable using Windows Powershell

To delete the environment variable in a windows machine using PowerShell you have to assign the blank string to that variable. As you can see below screenshot.

Conclusion

So in this article, we have seen all about how to set, edit, and delete environment variables in windows 11. Here I have more than one method to set, delete and edit windows environment variables as per your choice.

Environment variables is basically a process of storing variables and their values globally in the system so that programs, processes, and users determine where the configuration files, installation directory, drivers, and executable
are stored.

I hope this article is very useful for you. If you like this article please share and keep visiting for further interesting tutorials.

Ref:- Click Here

Thanks for your valuable time …

С помощью PowerShell вы можете получать, добавлять, удалять, или изменять значения переменных окружения (среды). В переменных окружения Windows хранит различную пользовательскую и системную информацию (чаще всего это пути к системным и временным папкам), которая используется операционной системой и приложениями, установленными на компьютере.

В Windows доступны несколько типов переменных окружения:

  • Переменные окружения процесса – создаются динамически и доступны только в текущем запущенном процесс
  • Пользовательские переменные окружения – содержат настройки конкретного пользователя и хранятся в его профиле (хранятся в ветке реестре
    HKEY_CURRENT_USER\Environment
    )
  • Системные переменные окружения – глобальные переменные окружения, которые применяются для все пользователей (хранятся в ветке
    HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
    )

    Переменные окружения хранятся в реестре Windows

Типы переменных окружения Windows указаны в порядке уменьшения приоритета. Т.е. значение переменной окружения %TEMP% в пользовательском профиле будет иметь больший приоритет, чем значение системной переменной окружения %TEMP%.

Для управления переменными окружениями обычно используется вкладка Advanced в свойствах системы. Чтобы открыть System Properties, выполните команду
SystemPropertiesAdvanced
и нажмите на кнопку Environment Variable.

В этом окне можно создать и отредактировать переменные среды для текущего пользователя или системные переменные окружения.

Настройка переменных окружения в окне свойств системы

Чтобы вывести полный список переменных окружения и их значения в PowerShell, выполните команду:

Get-ChildItem Env:

PowerShell - вывести все переменные окружения

Как вы видите, для доступа к переменным окружения в PowerShell используется отдельный виртуальный диск Env:, доступный через провайдер Environment.

Виртуальный диск с переменными окружения

Получить значение определенной переменной окружения Path:

Get-ChildItem env:Path

Получить значение переменной окружения из PowerShell

Т.к. переменные окружения, по сути, это файлы на виртуальном диске, нажатием кнопки TAB вы можете использовать автозавершение для набора имени переменной окружения.

Чтобы разбить значение переменной окружения на строки, выполните:

(Get-ChildItem env:Path).value -split ";"

Разбить значение переменной окружения на строки

Добавить значение в переменную окружения Path:

$Env:Path += ";c:\tools"

Однако это добавляет временное значение в переменную окружения
Path
. При следующей перезагрузке новое значение в переменной будет сброшено. Чтобы добавить постоянное значение в системную переменную окружения, используется такая конструкция:

$path = [System.Environment]::GetEnvironmentVariable("Path","Machine")
[System.Environment]::SetEnvironmentVariable("Path", $path + ";C:\tools", "Machine")
[System.Environment]::GetEnvironmentVariable("Path","Machine") -Split ";"

Чтобы изменить пользовательскую переменную окружения, замените в предыдущих командах область Machine на User.

Несмотря на то, что фактически переменные окружения и их значения хранятся в реестре, прямое изменение их значений в реестре используется редко. Причина в том, что текущий процесс при запуске считывает значение переменных окружения из реестра. Если вы измените их, процесс не будет уведомлён об этом.

Если вам нужно из PowerShell изменить в реестре значение переменной окружения, используются команды:

$variable = Get-ItemPropertyValue -Path 'HKCU:\Environment\' -Name 'Path'
$add_path = $variable + ';C:\Git\'
Set-ItemProperty -Path 'HKCU:\Environment\' -Name 'Path' -Value $add_path

Вы можете создать локальную переменную окружения. По умолчанию такая переменная окружения будет доступна только в текущем процессе (PowerShell), из которого она создана. После того, как процесс будет закрыт – переменная окружения будет удалена.

$env:SiteName = 'winitpro.ru'
Get-ChildItem Env:SiteName

Если нужно создать глобальную системную переменную (нужны права администратора), используйте команду:

[System.Environment]::SetEnvironmentVariable('siteName','winitpro.ru',"Machine")

Очистить и удалить глобальную переменную окружения:

[Environment]::SetEnvironmentVariable('siteName', $null, "Machine")

Environment variables may be helpful to programmers, system administrators, and other advanced users. They provide us with details about the environment wherein an application is running. In some instances, you can delete an environment variable. In other cases, you can change only its value.

Sometimes you might need to clear the environment variable on your Windows. But how can you do this? Keep reading to find out all the methods you can use to remove and change environment variables.

How to Unset Env Variable in Windows

The operating system’s environment makes use of data stored in environment variables. There is a lot of information we can learn from them about how the software works. Environment variables can be divided into two categories:

  • When a program is installed, the OS or driver sets these environment variables, which include information about system resources. These are called System Environment Variables. For instance, the windir variable will hold the location of Windows.
  • Information specific to a given user account is stored in User Environment Variables. Setting the PATH variable in order for the commands to run without having to provide the file path every time is an example of this.

There are ways to unset both types of Env Variables. You can do so by using the Environment Variables window, Power Shell, and Registry Editor.

Environment Variables Window

You can use Command Prompt to clear System and User Env Variables on your Windows PC. Here is how to clear System Env Variables:

  1. Launch Control Panel and select the System symbol.

  2. Select the “Advanced system settings” link on the left side, and if desired, shut the System control panel window.

  3. Select the Env Variables icon with your mouse or tapping device.

  4. Press “Delete” next to the variable you wish to delete at the bottom of the System variables section.

  5. Once you’re finished eliminating system variables, click “OK” to confirm.

To clear the User Env Variables, follow these steps:

  1. Click on the “User Accounts” button in the Control Panel.

  2. On the left, click or tap the “Change my environment variables” link, and if you wish, shut the User Accounts control panel window.

  3. Pick a variable you would like to remove outlined at the top of the User variables for <current user name> section, and press the “Delete” option.

  4. When you’re finished eliminating user variables from your account, select “OK” to confirm the deletion.

Power Shell

Power Shell can also be used to clear both types of Env Variables effectively. Here is how to clear System Env Variables:

  1. Launch a Windows PowerShell session in the elevated mode.

  2. Paste the following command into the elevated PowerShell:
    Get-ChildItem Env:

  3. Hit “Enter” and make a note of the name of the system variable you wish to unset.

  4. Enter the command below into the elevated PowerShell:
    [Environment]::SetEnvironmentVariable("[variable name]",$null,"Machine")

  5. Substitute [variable name] with the variable name you wish to remove in the command above.

  6. You may now exit the elevated Windows PowerShell.

If you want to delete User Env Variable, follow these steps:

  1. Run Windows PowerShell in elevated mode.

  2. In the elevated PowerShell prompt, paste the following command:
    Get-ChildItem Env:

  3. Press “Enter.”

  4. Now type or paste the command below:
    [Environment]::SetEnvironmentVariable("[variable name]",$null,"User")

  5. Hit “Enter” again and close PowerShell.

Registry Editor

Here’s how to clear System Env Variables using Registry Editor:

  1. To launch Registry Editor, press Win + R to open Run, input “regedit” into Run, then click on “OK.”
  2. On the left side of Registry Editor, navigate to the key shown below.
    HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

  3. Click or press and hold on the value name of the variable you wish to delete on the right side of the Environment key in Registry Editor. Then click or tap on “Delete.”

  4. Confirm by clicking on “Yes.”

  5. Close the Registry Editor.

And to clear user Env Variable, the steps are:

  1. To open Registry Editor, use Win + R to bring up Run, type “regedit” into Run, and then click “OK.”
  2. In the Registry Editor’s left pane, go to the key indicated below.
    HKEY CURRENT USER\Environment

  3. On Registry Editor, click or press and hold the value name of the variable you intend to remove on the right side of the Environment key. After that, select “Delete.”

  4. Confirm your selection by selecting “Yes.”

  5. Ensure that the Registry Editor is closed.

Additional FAQs

Why are Env Variables important?

The answer to the question, “What are environment variables?” is a relatively difficult one. As you can observe from this guide, dealing with Windows programs makes it tough to locate and observe environment variables.

Their management is handled in the background by the OS and the numerous apps and drivers you run on your computer. The OS and your existing programs, on the other hand, rely on them. Your system could malfunction if you mess about with the values of critical system variables without understanding what you’re doing.

What are the default Windows Environment Variables?

Each Windows PC has a vast array of variables. Variables such as OS, TEMP, and PATH are often utilized. You may find default values for Windows environment variables on websites like Wikipedia.

Have Control Over Your Env Variables

The same software used for clearing Env Variables can be used to edit or create new ones as well. However, if you’re not sure about it, it’s better to leave it to a professional. Since the variables are the backbone of your Operating System and software, messing with them can result in a system crash. This can be more expensive than asking a professional to deal with them in the first place.

Have you ever tried to clear Env Variables? Have you tried editing or creating new ones? Did you find it difficult? Let us know in the comment section below!

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Broadcom widcomm bluetooth driver windows 10
  • Имя события проблемы clr20r3 windows 7
  • Почему компьютер подключается к wifi без доступа к интернету windows 10
  • Как изменить цвет панели задач без активации windows 10
  • Windows three finger drag