How to set environment variable in windows
How to set the path and environment variables in Windows
Setting the path and environment variables will differ depending on the version of Windows you have on your computer. Choose a link below for your version of Windows.
Administrator privileges are usually required to modify the path and environment variables.
Setting the path and variables in Windows 10
You can edit other environment variables by highlighting the variable in the System variables section and clicking Edit. If you need to create a new environment variable, click New and enter the variable name and variable value.
To view and set the path in the Windows command line, use the path command.
Setting the path and variables in Windows 8
You can edit other environment variables by highlighting the variable in the System variables section and clicking Edit. If you need to create a new environment variable, click New and enter the variable name and variable value.
To view and set the path in the Windows command line, use the path command.
Setting the path and variables in Windows Vista and Windows 7
You can edit other environment variables by highlighting the variable in the System variables section and clicking Edit. If you need to create a new environment variable, click New and enter the Variable name and Variable value.
To view and set the path in the Windows command line, use the path command.
Setting the path and variables in Windows 2000 and Windows XP
The path is now managed by Windows 2000 and Windows XP and not the autoexec.bat or autoexec.nt files, as was done with earlier versions of Windows. To change the system environment variables, follow the steps below.
You can edit other environment variables by highlighting the variable in the System variables section and clicking Edit. If you need to create a new environment variable, click New and enter the Variable name and Variable value.
To view and set the path in the Windows command line, use the path command.
What is the default Windows %PATH%?
The path is based on programs installed on the computer, so there is no «default path.» However, the Windows minimum path is often the path below.
Keep in mind that as you install programs, the path is updated with the paths for the newly installed programs. So, if you have erased your path after installing other programs, those programs may be affected.
Setting path in the MS-DOS and Windows command line
To view and set the path in MS-DOS and in the Windows command line, use the path command.
How To Set Environment Variables
There are some things we just shouldn’t share with our code. These are often configuration values that depend on the environment such as debugging flags or access tokens for APIs like Twilio. Environment variables are a good solution and they are easy to consume in most languages.
Environment Variables.
Twilio’s helper libraries for example, look for the TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN environment variables if you instantiate a client without the two values. This way you don’t have to worry about accidentally pushing sensitive credentials to a place such as GitHub.
Windows Environment Variables
Setting environment variables in Windows is pretty hidden in several layers of settings dialogs. Just like most things in Windows, we will set environment variables using a graphical user interface. To open the respective interface you first have to open the Windows Run prompt. Do so by pressing the Windows and R key on your keyboard at the same time. Type sysdm.cpl into the input field and hit Enter or press Ok.
In the new window that opens, click on the Advanced tab and afterwards on the Environment Variables button in the bottom right of the window.
The window has two different sections. One is the list of environment variables that are specific to your user. This means they aren’t available to the other users. The other section contains the system-wide variables that are shared across all users.
Create a user specific variable by clicking the New button below the user-specific section. In the prompt you can now specify the name of your variable as well the value. Create a new variable with the name TWILIO_ACCOUNT_SID and copy your Twilio Account SID from the Console. Press Ok in the prompt to create the variable, followed by Ok on the Environment Variables window. You are all set now.
This should print the value that you saved in the environment variable.
macOS and Linux Distributions
In order to set environment variables on macOS or any UNIX based operating system you first have to figure out which shell you are running. You can do that by running in your terminal the command:
In order to set an environment variable we need to use the export command in the following format:
Replace youraccountsid with your actual Account SID from your Twilio Console. Save the file and open a new terminal instance to test if it worked by running:
You should see the value that you stored in it.
There are libraries for most programming languages to load these files. Here are a few:
Now all you need to do is consume the respective library and then you can use the environment variable. In Node.js the respective code would look like this:
Cloud Providers
Setting environment variables on your local development machine or in a VM is only half the work. What if we are hosting our application in a cloud environment such as Heroku, Azure or AWS or even wrap it in a Docker container? Luckily, all of these providers support ways to define environment variables. You can find instructions on how to set them in their documentations:
If you can’t find your cloud host among this list it doesn’t necessarily mean there is no way to configure environment variables. Make sure to check their documentation for more on it.
Summary
That’s it! Now you can set environment variables which means that you can take all of your environment based configuration values out of your code and make your code more flexible and safe!
Be mindful that these values are still stored in plain text. If you are planning to store very sensitive values you should look into something like a secret storage solution such as Vault.
How do I set system environment variables in Windows 10? [duplicate]
How do I set a system environment variable in Windows 10 (without using the registry editor)?
9 Answers 9
Update: After seeing lots of comments about setting environment variables without admin in Windows 10, I think I have found a way. I was not admin and could use PowerShell.
PowerShell method
There are different ways to work with environment variables and certain quirks with them in PowerShell so consult the link for details.
Old method (no longer available in newer Windows 10 updates, use PowerShell or see other answers)
Go into Settings and click on System.
Then on the left side click About and select System info at the bottom.
In the new Control Panel window that opens, click Advanced system settings on the left.
Now in the new window that comes up, select Environment Variables. at the bottom.
Still the same as ever: It’s in the old-style control panel’s “System” thingy. You can reach it with Win Break or by right-clicking the Start button.
From there, select “Advanced system settings” → “Environment Variables”.
Or you can do it the hard way and find some other entry point to the old-style control panel, like the Network and Sharing Center or the Desktop folder(!).
I typed «envir» in the «Search the web and Windows» box and selected «Edit environment variables for your account» under the «Best Match»
If by «system environment variables» you refer specifically to system-wide environment variables, then other answers have already covered this. However, if you want to edit both system-wide and user-specific environment variables then most (if not all) of these answers are inapplicable in general case.
If you attempt do that from a regular user account, then trying to access “Advanced system settings” will trigger an UAC prompt asking you for administrator password. If you enter the password, “Advanced system settings” will successfully open, but any user-specific changes you make there will apply to the corresponding administrator’s account (!), not to your original user’s account.
In order to solve this problem (i.e. in order to give regular users the opportunity to edit their own environment variables) Windows provides another way to access the “Environment Variables” dialog.
Open Control Panel. Open User Accounts applet. On the left-hand side of that applet you will see a link that says Change my environment variables. Click that link, and it will take you to the same “Environment Variables” dialog for your user’s environment variables.
If your user has administrator rights, you will be able to edit both sections of that dialog: user-specific environment variables (upper section) and system-wide environment variables (lower section). If you don’t have administrator rights, you will only be able to edit the upper section: your own user-specific environment variables.
This is the proper way to edit environment variables in all post-UAC versions of Windows, not what is suggested in the majority of the answers above.
Unfortunately, Windows 10 November update (version 1511) destroyed this functionality. The Change my environment variables link no longer works. It is there, but it is dead. So for the post-November version of Windows 10 the correct answer is: it is generally impossible to edit user-specific environment variables in version 1511 of Windows 10 from regular user accounts. Microsoft has destroyed Windows 10 with this update and Windows 10 is now unusable. It will remain the case until they fix these ridiculous bugs in 1511 version of the OS.
An alternative workaround is to use PowerShell features as described here https://technet.microsoft.com/en-us/library/ff730964.aspx
Windows 10 Anniversary Update (version 1607) released August 2, 2016 finally fixed this bug.
Create Environment Variable in Windows 10
Environment variables in an operating system are values that contain information about the system environment, and the currently logged in user. They existed in OSes before Windows as well, such as MS-DOS. Applications or services can use the information defined by environment variables to determine various things about the OS, for example, to detect the number of processes, the currently logged in user’s name, the folder path to the current user’s profile or the temporary files directory. Today, we will review a number of methods you can use to create a new user and system environment variable in Windows 10.
Example: A user environment variable.
Example: A system environment variable.
Windows 10 stores user environment variables under the following Registry key:
System variables are stored under the following key:
To Create a User Environment Variable in Windows 10,
Note: Re-open the required apps (e.g. Command Prompt) to make them read your new environment variable.
Tip: There are a number of other methods you can use to open the environment variables editor in Windows 10. First of all, you can create a special shortcut to open it directly. See Create Environment Variables Shortcut in Windows 10.
Also, there’s a special RunDLL command that you can use (Press Win + R and copy-paste it to the Run box):
Finally, you can right-click the This PC icon in File Explorer and select Properties from the context menu. Click the «Advanced System Settings» link on the left. In the next dialog, «System Properties», you will see the Environment Variables. button in the bottom of the Advanced tab. Moreover, the Advanced System Settings dialog can be directly opened with the systempropertiesadvanced command entered into the Run dialog.
Create a User Environment Variable in Command Prompt
Do not forget to restart your apps (e.g. Command Prompt) to make them read your new environment variable.
The setx command is a console tool that can be used to set or unset user and system environment variables. In the general case, the syntax is as follows:
Type setx /? in a command prompt to see more details about this tool.
Create a User Environment Variable in PowerShell
Similarly, you can create a system environment variable.
Create a System Environment Variable
Create a User Environment Variable in Command Prompt
The /M switch makes the setx command create a system variable.
Create a System Environment Variable in PowerShell
The last parameter of the SetEnvironmentVariable call tells it to register the given variable as a system variable.
Winaero greatly relies on your support. You can help the site keep bringing you interesting and useful content and software by using these options:
About Sergey Tkachenko
Sergey Tkachenko is a software developer from Russia who started Winaero back in 2011. On this blog, Sergey is writing about everything connected to Microsoft, Windows and popular software. Follow him on Telegram, Twitter, and YouTube.
Переменные среды в Windows: использование, список и таблицы
Переменная среды (environment variable) — текстовая короткая ссылка на элемент операционной системы Windows, предназначенная для получения быстрого доступа к объекту системы, или к данным о каталогах и конфигурации компьютера. Переменная среды (переменная окружения) позволяет быстро перейти к нужному месту на компьютере, без использования имени пользователя или полного пути к объекту.
Переменные окружения Windows используются в командной строке, в диалоговом окне «Выполнить» и адресной строке Проводника. Переменная среды может содержать информацию о настройках системы или данные о текущем пользователе компьютера.
Переменные среды Windows делятся на два вида:
Чаще всего переменные среды используются как путь к дискам, файлам или параметрам системы. Использование переменной среды позволяет быстро перейти к нужной директории операционной системы, без ввода полного пути, например, без ввода имени пользователя.
Переменные окружения часто используются при написании скриптов, или при работе в командной строке. Короткие переменные можно использовать вместо полного пути до файла или папки, например, при создании ярлыков, при вводе пути к объекту.
Пример использования переменной среды Windows
Рассмотрим следующий пример: пользователю нужно открыть системную папку «AppData», в которой находятся различные данные программ, установленных в операционную систему Windows. Скрытая папка «AppData» находится в профиле пользователя, обычно на диске «C:». Данные приложений расположены по пути:
Чтобы получить доступ к этой папке нужно выполнить несколько последовательных действий: открыть Проводник, включить в Windows отображение скрытых папок и файлов, а затем пройти по всему пути до нужной папки.
При помощи переменной «%APPDATA%» (переменная используется без кавычек) можно сразу открыть нужную директорию в системе, без ввода имени пользователя, включения отображения скрытых папок, ввода полного пути. Это экономит много времени.
Чтобы открыть нужный каталог достаточно лишь ввести «%APPDATA%» в поле поиска Windows, в адресную строку Проводника или в диалоговое окно «Выполнить», а затем нажать на клавишу «Enter».
Переменные среды Виндовс заключены в специальный оператор «%», который находится с двух сторон названия переменной. Это необходимо, чтобы система могла обработать запрос.
Пользователь может самостоятельно создавать переменные среды или изменять существующие. В статье мы рассмотрим несколько способов просмотра переменных среды и самостоятельное создание переменной. В руководстве вы найдете таблицу со списком переменных, применяемых в операционных системах Windows 10, Windows 8.1, Windows 8, Windows 7.
Как посмотреть переменные среды Windows 10
Сейчас мы посмотрим, как получить доступ к переменным средам в операционной системе Windows 10. В других версиях Windows необходимо выполнить аналогичные действия.
Чтобы посмотреть переменные окружения Windows 10, выполните следующее:
Доступ к переменным средам из реестра Windows
Есть возможность получить доступ к переменным средам из системного реестра Windows. Пользователю нужно будет открыть редактор реестра, а затем пройти по пути до определенной ветки.
Системные переменные среды находятся по следующему пути:
Переменные среды локального пользователя расположены в следующей ветке реестра:
Вы можете создать в редакторе реестра новые переменные или изменить существующие.
Как посмотреть все переменные среды в командной строке
Пользователь может получить список переменных среды при помощи системного инструмента — командной строки Windows.
В cmd переменные среды открываются следующим образом:
Для получения списка переменных в виде текстового файла, выполните в командной строке команду:
После выполнения этой команды, на Локальном диске «C:» появится текстовый файл с именем «Variables» (имя можно использовать любое), в котором находится список переменных среды Windows.
На моем компьютере файл имеет следующее содержание:
Открытие списка переменных среды в Windows PowerShell
Открытие списка переменных среды возможно при помощи системного средства Windows PowerShell.
Выполните следующие действия:
Создание переменной среды в Windows
Пользователь может самостоятельно создать новую переменную для открытия директорий на компьютере, или для запуска программ.
На этом примере я создам отдельную переменную среды для запуска программы TeamViewer.
Подобным способом, после ввода переменной в адресную строку Проводника, выполняется запуск программы или открытие директории на ПК.
Переменная среды пути «Path» содержит список директорий на компьютере, в которых система должна искать исполняемые файлы. Переменная среды пути «PATH» не добавляется к исполняемым файлам, а только к директориям, где находятся данные файлы.
При необходимости, пользователь может удалить ненужную переменную из операционной системы Windows.
Список переменных среды Windows в таблице
Для удобства посетителей сайта я собрал в общую таблицу переменные, их описание и значения в операционной системе Windows. В подавляющем большинстве случаев, системная папка расположена на диске «C:», поэтому пути в значениях даны для этого диска.
Выводы статьи
Переменные окружения Windows позволяют пользователю экономить время во время работы на компьютере. Переменными средами Windows могут пользоваться обычные пользователи или системные администраторы для быстрого доступа к объектам операционной системы, чтобы открыть нужную директорию на компьютере, или запустить программу.