
Overview –
Environment Variables in Windows
It seems that you’re learning to program and trying to refresh environment variables in Windows 11 without rebooting your computer and restarting your project and disrupting the workflow.
The Windows OS provides a way for system administrators to change the values of environment variables in the registry. A special section of the registry called “Environment” contains all user-defined environment variables. You can modify these values through the use of the “Regedit” application.
An environment variable is a named object that contains data used by one or more applications. The environment variables are stored in the registry, where they can be viewed and edited using standard tools.
By the end of this article, you’ll be able to refresh environment variables in Windows without rebooting your computer:
Using Chocolatey Package Manager (Recommended)
Using Command Prompt
What are Environment
Variables in Windows
Variables are used to store many sorts of data. System settings, inventory statuses, and other data can be stored in these variables. Environment Variables are a type of variable that contains environmental information about a computer. The environment variables in Windows can be used to make changes to the system without having to edit the registry.
The variables in the environment are used to define variables for a variety of purposes. Windows itself does not require them. You put up these variables, and they determine how Windows runs it. You can use them, for example, to identify your user or its location.
Environment Variables in Windows help you to assign values that will be used during the process of execution of any command on your computer. This will allow these commands to execute on a given set of values, altering their appearance.
1. Refresh
Environment Variables via Chocolatey Package Manager
(Recommended)
Step 1: Open the Command Prompt from the Start menu, copy and paste the following command to install chocolatey package manager on your PC:
@”%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe” -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command “[System.Net.ServicePointManager]::SecurityProtocol = 3072; iex ((New-Object System.Net.WebClient).DownloadString(‘https://community.chocolatey.org/install.ps1’))” && SET “PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin”
Command to install Chocolatey using CMD
Step 2: After installing the Chocolatey Package Manager, type the command “refreshenv” (without quotation marks) to refresh system variables.
Refresh environment variables using chocolatey
NOTE: After the installation of the chocolatey package manager, every time you type and execute the “refreshenv” command, the environment variables will be refreshed immediately, without the need to restart the computer.
2. Refresh
Environment Variables via Command Prompt (CMD)
Step 1: In the Start menu, search for Command Prompt and run it as an administrator.
Command Prompt (CMD) Icon
Step 2: Type the command: “set PATH = c” (without quotation marks), press the enter key, and restart the Command Prompt.
“set PATH = c” command
Step 3: Type the command: “echo %PATH%” (without quotation marks) and press the enter key to reset system variables using CMD.
“echo %Path%” command
NOTE: After installing the PostgreSQL (PgAdmin 4), I tried this way to update environment variables, and it worked nicely.
FAQs Related to
Environment Variables
What
is the difference between System variables and Environment
variables?
System environment variables are globally accessed by all users. The user Environment variables are specific only to the currently logged-in user and remain the default for the other users.
Where are the
system variables stored in the registry?
The actual location of system variables in the registry is: HKEY_LOCAL_MACHINE > SYSTEM > CurrentControlSet > Control > Session Manager > Environment.
Are environment
variables stored in memory?
Environment variables and command line parameters are kept together at the top of the process memory structure, above the layer.
Next
Steps
When you change the value of an environment variable in windows, the changes are not applied to your current windows session. You have to either log out and log in again or restart your device. But, in this article, we’ve covered how to reset environment variables in Windows 11 without rebooting the computer.
Variables can be accessed through DOS commands by typing “set”. They can also be accessed through other programs such as PowerShell and Command Prompt using the Control Panel applet or any other number of available applications for manipulating environment variables.
It’s important to know that the changes you make in the environment variables will be modified for other users of the system as well. They should not, however, be confused with Environment Variables in Windows.
Further, customize your computer’s configuration by referring to the related articles below.
Update
I haven’t used Windows for over a decade, but this page gets a lot of hits, so I
leave it here assuming and hopeful it is helpful.
—
I find it quite annoying that whenever I read instructions that include adding
an environment path variable you are asked to reboot your machine for changes to
take effect. I know there has GOT to be a way to do it. Well, I know a way, but
it’s someway kludgy.
Here is how I do it (I’m really hoping someone will comment and tell me a better
way)
-
Open your system properties window. Screenshots below are for Vista:
-
Open you Environment Variables Window.
-
Double Click on you Path (if you want to just change you path for your login,
use the top one, if you want to change it for all logins, use the bottom one) -
Append the path you would like to add, separated with a semi-colon. Below, I
am adding C:\CmdShortcuts
…
Now, reboot your computer! Argh! J/K
Here is the kludgy hack that I use so I don’t have to reboot. (But it will not
work in all cases, which is why I don’t like it, so please, if you know of a
batch script or something I can run that will apply the changes made to the
environment variables without rebooting, please post a comment.)
Open a comment window and type SET PATH=%PATH%;C:\CmdShortcuts
You can type PATH again to see your path variables. Your new path should be
added. The problem with this is that this new path variable is only good inside
this command window. If you are doing command line stuff this works, but if you
close your cmd window the change is lost.
Изменение переменных окружения без перезагрузки
От: |
DemAS |
http://demas.me | |
Дата: | 04.12.07 06:30 | ||
Оценка: |
6 (1) |
Возможно ли в Win менять значения переменных окружения буз перезагрузки?
Да и вообще, существует ли удобный инструментарий для работы с ними. Стандартный похож на издевательство ибо:
— если переменная длинная и является перечислением (типа PATH), то фиг в ней что найдешь в этом маленьком окошке, который предлагается для ее редактирования
— чтобы ввести новую переменную нужно нажать Добавить, нужно что-то написать в очень маленьком окошке и нажать ОК
IMHO обычный текстовый файл был бы и то удобнее, и не было бы очередной проблемы
— резервного копирования эих переменных
Кстати, почему после изменения переменной окрыжения нужно обязательно перезагружаться иначе она не вступит в силу? Что за такие важные структуры инициализуруются в windows internals, что я не могу прописать путь где ОС будет искать файлы без ее перезагрузки? Бред? Или я что-то не понимаю?
Кроме того надоели такие вещи:
После установки компилятора необходимо проверить, что в переменной окружения PATH прописан путь:
<путь к компилятору>bin\i386-win32\;
Причём, он должен там быть раньше, чем пути к остальным FPC, если их в системе несколько. Кроме того, если в системе установлен, например, MinGW, то, если, в PATH путь к нему прописан раньше, чем к FPC, то будет использован не ld из FPC, а ld из MinGW и ничего собрать не удастся.
В общем, может кто-то нашел что-то удобное, чтобы сосуществовать рядом с этим безобразием?
p.s. Linux не предлагать
… << RSDN@Home 1.2.0 alpha rev. 786>>
Re: Изменение переменных окружения без перезагрузки
От: |
Sergeant_BY |
||
Дата: | 04.12.07 07:07 | ||
Оценка: |
4 (1) |
Здравствуйте, DemAS, Вы писали:
DAS>Возможно ли в Win менять значения переменных окружения буз перезагрузки?
Без перезагрузки процесса которому нужно перечитать обновленный environment — нет.
Без перезагрузки всей системы — пожалуй да.
DAS> Да и вообще, существует ли удобный инструментарий для работы с ними. Стандартный похож на издевательство ибо:
DAS> — если переменная длинная и является перечислением (типа PATH), то фиг в ней что найдешь в этом маленьком окошке, который предлагается для ее редактирования — чтобы ввести новую переменную нужно нажать Добавить, нужно что-то написать в очень маленьком окошке и нажать ОК
setx path «%PATH%;C:\New Folder»
setx — из ресурскита к XP, например.
DAS> IMHO обычный текстовый файл был бы и то удобнее, и не было бы очередной проблемы
Удобнее чем и в каком виде?
Кстати «эти маленькие окошки» — просто frontend к редактированию значений в HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment Т.е. если удобнее для этого пользоваться текстовыми файлами (для импорта в regedit, например) — пожалуйста.
Но запуск/перезапуск процесса которому нужно перечитать изменения понадобится по любому.
DAS> — резервного копирования эих переменных
set > backup_env.txt ?
DAS> Кстати, почему после изменения переменной окрыжения нужно обязательно перезагружаться иначе она не вступит в силу? Что за такие важные структуры инициализуруются в windows internals, что я не могу прописать путь где ОС будет искать файлы без ее перезагрузки? Бред? Или я что-то не понимаю?
Оккрываю System properties->Advanced->Environment, добавляю какую-нибудь лабуду в конце %PATH%, нажимаю ОК.
Запускаю cmd, пишу set и вижу в %PATH% ту самую лабуду.
Что я делаю не так?
DAS> Кроме того надоели такие вещи:
DAS>
DAS> После установки компилятора необходимо проверить, что в переменной окружения PATH прописан путь:
DAS><путь к компилятору>bin\i386-win32\;
DAS>Причём, он должен там быть раньше, чем пути к остальным FPC, если их в системе несколько. Кроме того, если в системе установлен, например, MinGW, то, если, в PATH путь к нему прописан раньше, чем к FPC, то будет использован не ld из FPC, а ld из MinGW и ничего собрать не удастся.
DAS> В общем, может кто-то нашел что-то удобное, чтобы сосуществовать рядом с этим безобразием?
DAS> p.s. Linux не предлагать
А в Linux’е разве по другому?
Предложите другой разумный способ указания путей для поиска исполняемых файлов для запуска с системой приоритетов…
Re: Изменение переменных окружения без перезагрузки
От: |
DOOM |
||
Дата: | 04.12.07 07:11 | ||
Оценка: |
2 (1) |
Здравствуйте, DemAS, Вы писали:
DAS>Возможно ли в Win менять значения переменных окружения буз перезагрузки?
Конечно.
DAS> Да и вообще, существует ли удобный инструментарий для работы с ними. Стандартный похож на издевательство ибо:
DAS> — если переменная длинная и является перечислением (типа PATH), то фиг в ней что найдешь в этом маленьком окошке, который предлагается для ее редактирования
DAS> — чтобы ввести новую переменную нужно нажать Добавить, нужно что-то написать в очень маленьком окошке и нажать ОК
DAS> IMHO обычный текстовый файл был бы и то удобнее, и не было бы очередной проблемы
DAS> — резервного копирования эих переменных
Ну тут да… Косяк. Можно напрямую через реестр, если этот способ можно назвать удобным…
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment — это системные переменные
HKEY_CURRENT_USER\Environment — пользовательские
Кроме того, в Support Tools’ах есть утилита setx, которая, в отличие от set позволяет делать постоянные изменения в переменных окружения.
DAS> Кстати, почему после изменения переменной окрыжения нужно обязательно перезагружаться иначе она не вступит в силу? Что за такие важные структуры инициализуруются в windows internals, что я не могу прописать путь где ОС будет искать файлы без ее перезагрузки? Бред? Или я что-то не понимаю?
Видать что-то не понимаешь. В винде, как и во многих других ОС, окружение привязано к процессу — поэтому, чтобы отразить изменения в окружении надо перезапустить процесс. Т.е. поменял PATH, перезапусти cmd.exe и он уже будет с новыми путями.
DAS> Кроме того надоели такие вещи:
DAS>
DAS> После установки компилятора необходимо проверить, что в переменной окружения PATH прописан путь:
DAS><путь к компилятору>bin\i386-win32\;
DAS>Причём, он должен там быть раньше, чем пути к остальным FPC, если их в системе несколько. Кроме того, если в системе установлен, например, MinGW, то, если, в PATH путь к нему прописан раньше, чем к FPC, то будет использован не ld из FPC, а ld из MinGW и ничего собрать не удастся.
Не вижу проблемы. Сделай себе 2 скрипта — один при запуске cmd добавляет в PATH пути к MinGW, другой к чему-нибудь еще. Запускай нужный и не засоряй общесистемные переменные…
DAS> В общем, может кто-то нашел что-то удобное, чтобы сосуществовать рядом с этим безобразием?
Ну что знал, то предложил…
DAS> p.s. Linux не предлагать
А там по сути также. Переменные окружения вещь очень старая и ведет себя так, как это было придумано десятилетия назад.
Re[2]: Изменение переменных окружения без перезагрузки
От: |
DemAS |
http://demas.me | |
Дата: | 04.12.07 07:18 | ||
Оценка: |
Здравствуйте, Sergeant_BY, Вы писали:
S_B>setx path «%PATH%;C:\New Folder»
S_B>setx — из ресурскита к XP, например.
Спасибо, гораздо удобнее.
DAS>> — резервного копирования эих переменных
S_B>set > backup_env.txt ?
А обратно как?
Понимаю, что можно написать скрипт, который сформирует набор команд для setx, но может есть что-то готовое.
S_B>Оккрываю System properties->Advanced->Environment, добавляю какую-нибудь лабуду в конце %PATH%, нажимаю ОК.
S_B>Запускаю cmd, пишу set и вижу в %PATH% ту самую лабуду.
S_B>Что я делаю не так?
Я тоже вижу. Но если я пытаюсь запустить exe-к из каталога, находящегося в добавленной директории — система говорит, что не знает такого.
Хотя возможно это я ступил — наверное надо было перезапустить cmd.
DAS>> p.s. Linux не предлагать
S_B>А в Linux’е разве по другому?
Не знаю. Но на всякий случай предупредил. Спасибо
… << RSDN@Home 1.2.0 alpha rev. 786>>
Re: А вот в лиинуксе!….
От: |
Sheridan |
||
Дата: | 04.12.07 07:47 | ||
Оценка: |
—
…belive in the matrix…
Posted via RSDN NNTP Server 2.1 beta
Matrix has you…
- Переместить
- Удалить
- Выделить ветку
Пока на собственное сообщение не было ответов, его можно удалить.
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
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
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
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
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
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
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
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 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
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
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 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
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
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
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
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 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
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.