Windows set environment variable from file

On windows/cygwin, i want to be able save the PATH variable to file on one machine and load it onto the other machine; for storing the variable i am doing: echo %PATH% > dat however, not sure...

On windows/cygwin, i want to be able save the PATH variable to file on one machine and load it onto the other machine;

for storing the variable i am doing:

echo %PATH% > dat

however, not sure how to load it later.

set PATH=???????

Thanks
Rami

asked Jan 7, 2012 at 3:08

sramij's user avatar

2

Just use: set /P PATH=< dat

You must note that echo %PATH% > dat insert an additional space after %PATH% value; that space may cause problems if an additional path is later added to PATH variable. Just eliminate the extra space this way: echo %PATH%> dat.

answered Jan 11, 2012 at 4:48

Aacini's user avatar

AaciniAacini

63.7k12 gold badges70 silver badges105 bronze badges

3

echo %PATH% will fail if the PATH contains an unquoted & or ^ (this is not likely, but certainly possible)

A more reliable solution is to use:

setlocal enableDelayedExpansion
echo !path!>dat

Then you can use Aacini’s suggested method of reading the value back in

set /p "PATH=" <dat

answered Jan 7, 2012 at 14:55

dbenham's user avatar

dbenhamdbenham

126k28 gold badges245 silver badges383 bronze badges

This might be evil but on Windows I am using this:

for /F %%g in (dat) do set PATH=%%g

and this to write the file because I had trouble with spaces

echo>dat %PATH%

answered Mar 27, 2013 at 16:08

SpacedMonkey's user avatar

SpacedMonkeySpacedMonkey

2,7051 gold badge15 silver badges17 bronze badges

1

Being dependent upon Cygwin, how how about putting the command in your saved file, e.g.:

echo "export PATH=$PATH" > dat

Then sourcing the script later to set the path:

. ./dat

Note that «sourcing» the script (vs. just executing it) is required for it to modify your current environment — and not just new child environments.

answered Jan 7, 2012 at 3:13

ziesemer's user avatar

ziesemerziesemer

27.4k8 gold badges87 silver badges94 bronze badges

1

The following sample works even with spaces and dot in the path value:

@REM Backup PATH variable value in a file
@REM Set PATHBACKUP variable with value in the file

@echo %PATH% > pathvalue.txt
@type pathvalue.txt
@for /f "delims=" %%l in (pathvalue.txt) do (
  @set line=%%l
)
@set PATHBACKUP=%line%
@echo %PATHBACKUP%

answered Jun 9, 2021 at 20:12

efdummy's user avatar

efdummyefdummy

6741 gold badge8 silver badges9 bronze badges

I know set command sets environment variables temporarily while set command sets environment variables permanently.

This command exports current environment variable path to a file

echo %path% > path.txt

Is there a way to set environment variable by importing from a file, something like this?

set %path% < path.txt

I tried env:PATH = (Get-Content path.txt) with powershell but got this error.

enter image description here

asked Jan 26, 2021 at 10:35

JJJohn's user avatar

JJJohnJJJohn

3431 gold badge6 silver badges21 bronze badges

3

You can try the commands below to set/change the environment variable while reading it from a file. In the following example, the PATH variable is set and its content will be replaced.

$env:PATH = (Get-Content path.txt)

To add to the environment variable:

$env:PATH += (Get-Content path.txt)

You can also use [Environment]::SetEnvironmentVariable as described here to make the changes permanent.

[Environment]::SetEnvironmentVariable($env:Path, $mypath, "Process")

answered Jan 26, 2021 at 13:28

Reddy Lutonadio's user avatar

Reddy LutonadioReddy Lutonadio

15.3k4 gold badges14 silver badges34 bronze badges

2

Introduction

Environment variables are key-value pairs a system uses to set up a software environment. The environment variables also play a crucial role in certain installations, such as installing Java on your PC or Raspberry Pi.

In this tutorial, we will cover different ways you can set, list, and unset environment variables in Windows 10.

How to set environment variables in Windows

Prerequisites

  • A system running Windows 10
  • User account with admin privileges
  • Access to the Command Prompt or Windows PowerShell

Check Current Environment Variables

The method for checking current environment variables depends on whether you are using the Command Prompt or Windows PowerShell:

List All Environment Variables

In the Command Prompt, use the following command to list all environment variables:

set
List all environment variables using the Command Prompt

If you are using Windows PowerShell, list all the environment variables with:

Get-ChildItem Env:
List all environment variables using Windows PowerShell

Check A Specific Environment Variable

Both the Command Prompt and PowerShell use the echo command to list specific environment variables.

The Command prompt uses the following syntax:

echo %[variable_name]%
Checking a specific environment variable using the Command Prompt

In Windows PowerShell, use:

echo $Env:[variable_name]
Checking a specific environment variable using Windows PowerShell

Here, [variable_name] is the name of the environment variable you want to check.

Follow the steps to set environment variables using the Windows GUI:

1. Press Windows + R to open the Windows Run prompt.

2. Type in sysdm.cpl and click OK.

Run sysdm.cpl

3. Open the Advanced tab and click on the Environment Variables button in the System Properties window.

Find the Environment Variables button in the Advanced tab

4. The Environment Variables window is divided into two sections. The sections display user-specific and system-wide environment variables. To add a variable, click the New… button under the appropriate section.

Click on the New... button to add a variable

5. Enter the variable name and value in the New User Variable prompt and click OK.

Enter the new variable name and value

Set Environment Variable in Windows via Command Prompt

Use the setx command to set a new user-specific environment variable via the Command Prompt:

setx [variable_name] "[variable_value]"

Where:

  • [variable_name]: The name of the environment variable you want to set.
  • [variable_value]: The value you want to assign to the new environment variable.

For instance:

setx Test_variable "Variable value"
Setting a user-specific environment variable via the Command Prompt

Note: You need to restart the Command Prompt for the changes to take effect.

To add a system-wide environment variable, open the Command Prompt as administrator and use:

setx [variable_name] "[variable_value]" /M
Setting a system environment variable via the Command Prompt

Unset Environment Variables

There are two ways to unset environment variables in Windows:

Unset Environment Variables in Windows via GUI

To unset an environment variable using the GUI, follow the steps in the section on setting environment variables via GUI to reach the Environment Variables window.

In this window:

1. Locate the variable you want to unset in the appropriate section.

2. Click the variable to highlight it.

3. Click the Delete button to unset it.

Unset environment variables in Windows via GUI

Unset Environment Variables in Windows via Registry

When you add an environment variable in Windows, the key-value pair is saved in the registry. The default registry folders for environment variables are:

  • user-specific variables: HKEY_CURRENT_USEREnvironment
  • system-wide variables: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment

Using the reg command allows you to review and unset environment variables directly in the registry.

Note: The reg command works the same in the Command Prompt and Windows PowerShell.

Use the following command to list all user-specific environment variables:

reg query HKEY_CURRENT_USEREnvironment
Listing all user-specific environment variables in the registry

List all the system environment variables with:

reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment"
Listing all system environment variables in the registry

If you want to list a specific variable, use:

reg query HKEY_CURRENT_USEREnvironment /v [variable_name]
Listing a specific user environment variable in the registry

or

reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v [variable_name]
Listing a specific system environment variable in the registry

Where:

  • /v: Declares the intent to list a specific variable.
  • [variable_name]: The name of the environment variable you want to list.

Use the following command to unset an environment variable in the registry:

reg delete HKEY_CURRENT_USEREnvironment /v [variable_name] /f
Unsetting a user-specific environment variable from the registry

or

reg delete "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v [variable_name] /f
Unsetting a system environment variable from the registry

Note: The /f parameter is used to confirm the reg delete command. Without it, entering the command triggers the Delete the registry value EXAMPLE (Yes/No)? prompt.

Run the setx command again to propagate the environment variables and confirm the changes to the registry.

Note: If you don’t have any other variables to add with the setx command, set a throwaway variable. For example:

setx [variable_name] trash

Conclusion

After following this guide, you should know how to set user-specific and system-wide environment variables in Windows 10.

Looking for this tutorial for a different OS? Check out our guides on How to Set Environment Variables in Linux and How to Set Environment Variables in MacOS.

!

If you use logical ( && or || ) or modulus (%) operators, enclose the expression string in quotation marks. Any non-numeric strings in the expression are considered environment variable names, and their values are converted to numbers before they are processed. If you specify an environment variable name that is not defined in the current environment, a value of zero is allotted, which allows you to perform arithmetic with environment variable values without using the % to retrieve a value.

If you run set /a from the command line outside of a command script, it displays the final value of the expression.

Numeric values are decimal numbers unless prefixed by 0Г— for hexadecimal numbers or 0 for octal numbers. Therefore, 0Г—12 is the same as 18, which is the same as 022.

Delayed environment variable expansion support is disabled by default, but you can enable or disable it by using cmd /v.

When creating batch files, you can use set to create variables, and then use them in the same way that you would use the numbered variables %0 through %9. You can also use the variables %0 through %9 as input for set.

If you call a variable value from a batch file, enclose the value with percent signs (%). For example, if your batch program creates an environment variable named BAUD, you can use the string associated with BAUD as a replaceable parameter by typing %baud% at the command prompt.

Examples

To set an environment variable named INCLUDE so the string c:directory is associated with it, type:

You can then use the string c:directory in batch files by enclosing the name INCLUDE with percent signs (%). For example, you can use dir %include% in a batch file to display the contents of the directory associated with the INCLUDE environment variable. After this command is processed, the string c:directory replaces %include%.

To use the set command in a batch program to add a new directory to the PATH environment variable, type:

To display a list of all of the environment variables that begin with the letter P, type:

Источник

Setting and getting Windows environment variables from the command prompt?

When I use the set command, it isn’t accessible in a new cmd session.

6 Answers 6

To make the environment variable accessible globally you need to set it in the registry. As you’ve realised by just using:

you are just setting it in the current process space.

According to this page you can use the setx command:

setx is built into Windows 7, but for older versions may only be available if you install the Windows Resource Kit

ZaOrY

We can also use «setx var variable /M» to set the var to system environment variable level instead of user level.

Note: This command should be run as administrator.

geyHC

/M for set system environment variable level instead of user level like @Minh Chau answer

RESTART command line (if you don’t restart command line, environment variable will not work)

f5jNP

You can use setx env var [/M] as mentioned above. If it doesn’t take effect you can use refreshenv to refresh environment variables. You don’t have to restart your computer, explorer.exe or your command prompt to do that.

Edit: apparantly refreshenv doesn’t come naturally with Windows, so here’s the source: https://pastebin.com/1fJqA0pT
Save as RefreshEnv.cmd and place it in a folder that’s included in your PATH environment variables

IS7hd

System variables can be set through CMD and registry For ex. reg query «HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment» /v PATH

All the commonly used CMD codes and system variables are given here: Set Windows system environment variables using CMD.

Open CMD and type Set

You will get all the values of system variable.

Type set java to know the path details of java installed on your window OS.

Источник

How to Set Environment Variable in Windows

Home » SysAdmin » How to Set Environment Variable in Windows

Environment variables are key-value pairs a system uses to set up a software environment. The environment variables also play a crucial role in certain installations, such as installing Java on your PC or Raspberry Pi.

In this tutorial, we will cover different ways you can set, list, and unset environment variables in Windows 10.

setting environment variables in windows 01 1

Check Current Environment Variables

The method for checking current environment variables depends on whether you are using the Command Prompt or Windows PowerShell:

List All Environment Variables

In the Command Prompt, use the following command to list all environment variables:

setting environment variables in windows 02

If you are using Windows PowerShell, list all the environment variables with:

setting environment variables in windows 03

Check A Specific Environment Variable

Both the Command Prompt and PowerShell use the echo command to list specific environment variables.

The Command prompt uses the following syntax:

setting environment variables in windows 04

In Windows PowerShell, use:

setting environment variables in windows 05

Here, [variable_name] is the name of the environment variable you want to check.

Set Environment Variable in Windows via GUI

Follow the steps to set environment variables using the Windows GUI:

1. Press Windows + R to open the Windows Run prompt.

2. Type in sysdm.cpl and click OK.

setting environment variables in windows 06

3. Open the Advanced tab and click on the Environment Variables button in the System Properties window.

setting environment variables in windows 07

4. The Environment Variables window is divided into two sections. The sections display user-specific and system-wide environment variables. To add a variable, click the New… button under the appropriate section.

setting environment variables in windows 08

5. Enter the variable name and value in the New User Variable prompt and click OK.

setting environment variables in windows 09

Set Environment Variable in Windows via Command Prompt

Use the setx command to set a new user-specific environment variable via the Command Prompt:

setting environment variables in windows 11

Note: You need to restart the Command Prompt for the changes to take effect.

To add a system-wide environment variable, open the Command Prompt as administrator and use:

setting environment variables in windows 12

Unset Environment Variables

There are two ways to unset environment variables in Windows:

Unset Environment Variables in Windows via GUI

To unset an environment variable using the GUI, follow the steps in the section on setting environment variables via GUI to reach the Environment Variables window.

1. Locate the variable you want to unset in the appropriate section.

2. Click the variable to highlight it.

3. Click the Delete button to unset it.

setting environment variables in windows 10

Unset Environment Variables in Windows via Registry

When you add an environment variable in Windows, the key-value pair is saved in the registry. The default registry folders for environment variables are:

Using the reg command allows you to review and unset environment variables directly in the registry.

Note: The reg command works the same in the Command Prompt and Windows PowerShell.

Use the following command to list all user-specific environment variables:

setting environment variables in windows 13

List all the system environment variables with:

setting environment variables in windows 14

If you want to list a specific variable, use:

setting environment variables in windows 15

setting environment variables in windows 16

Use the following command to unset an environment variable in the registry:

setting environment variables in windows 17

setting environment variables in windows 18

Note: The /f parameter is used to confirm the reg delete command. Without it, entering the command triggers the Delete the registry value EXAMPLE (Yes/No)? prompt.

Run the setx command again to propagate the environment variables and confirm the changes to the registry.

Note: If you don’t have any other variables to add with the setx command, set a throwaway variable. For example:

After following this guide, you should know how to set user-specific and system-wide environment variables in Windows 10.

Looking for this tutorial for a different OS? Check out our guides on How to Set Environment Variables in Linux and How to Set Environment Variables in MacOS.

Источник

Setting a system environment variable from a Windows batch file?

Is it possible to set a environment variable at the system level from a command prompt in Windows 7 (or even XP for that matter). I am running from an elevated command prompt.

When I use the set command ( set name=value ), the environment variable seems to be only valid for the session of the command prompt.

7 Answers 7

The XP Support Tools (which can be installed from your XP CD) come with a program called setx.exe :

I think Windows 7 actually comes with setx as part of a standard install.

Simple example for how to set JAVA_HOME with setx.exe in command line:

This will set environment variable «JAVA_HOME» for current user. If you want to set a variable for all users, you have to use option «-m». Here is an example:

Note: you have to execute this command as Administrator.

Note: Make sure to run the command setx from an command-line Admin window

1 like so: setx /M JAVA_HOME «C:Progra

If you set a variable via SETX, you cannot use this variable or its changes immediately. You have to restart the processes that want to use it.

Use the following sequence to directly set it in the setting process too (works for me perfectly in scripts that do some init stuff after setting global variables):

For XP, I used a (free/donateware) tool called «RAPIDEE» (Rapid Environment Editor), but SETX is definitely sufficient for Win 7 (I did not know about this before).

System variables can be set through CMD and registry For ex. reg query «HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment» /v PATH

All the commonly used CMD codes and system variables are given here: Set Windows system environment variables using CMD.

Open CMD and type Set

You will get all the values of system variable.

Type set java to know the path details of java installed on your window OS.

photo

Just in case you would need to delete a variable, you could use SETENV from Vincent Fatica available at http://barnyard.syr.edu/

vefatica. Not exactly recent (’98) but still working on Windows 7 x64.

SetX is the command that you’ll need in most of the cases.Though its possible to use REG or REGEDIT

Источник

Adblock
detector

Windows uses environment variables to store valuable information about system processes, resource usage, file path, and more.

Let’s learn how to set up system environment variables in Windows.

What are Environment Variables in Windows?

Environment variables help Windows set up a software environment and act as information containers for all applications running on the operating system. Imagine an application that wants to know the path to a specific file on your computer. The program can either go through the entire system and keep searching until it finds the file. A more innovative way is to call the PATH environment variable that contains the paths to all the system files.

Moreover, system environment variables also affect the installation of Java Development Kit, Java Runtime Environment, and other essential software. Just like the above examples, there are a plethora of small and extensive real-world use cases of environment variables that overall make Windows a snappier version of itself.

Types of Environment Variables

Windows creates and uses several environment variables, some of which are user-dependent and others remain the same for all users on a single machine. We can categorize environment variables using user dependence as a parameter and term them as system environment variables and user environment variables.

Information like the location of temporary files from an account, location of your user profile, etc., are stored under user variables. Windows gives the user account the privilege to edit the user variables, but other user accounts cannot edit them.

Other than this, Windows contains system environment variables created by the operating system, programs, drivers, and more. You cannot tweak the system environment variables, but Windows offers the option to tweak user environment variables’ values.

Methods to Setup System Environment Variables in Windows

You can set up system environment variables using different methods in Windows. Although the command line methods remain unchanged for all Windows versions, the GUI-based methods differ slightly for different Windows versions. Let’s look at all these methods in-depth.

GUI Based Methods

The GUI-based methods include using the Start search menu, the Run Window, and the Settings menu to tweak system environment variables. Let’s look at how you can access the GUI from various Windows versions.

Steps for Windows 11

Click on the Start Menu and search for “environment variables.”

The “Edit the system environment variables” option will appear in the search results. Click on the same, and Windows 11 will display the list of all environment variables.

Steps for Windows 10

Go to settings and enter the “About” menu.

Now go to “Advanced system settings.” The System Properties dialogue box should appear on your screen.

Click on the “Advanced” tab and select “Environment Variables.” Windows 10 will now display the entire list of user and system variables stored on your computer.

Using Run Window

Press Windows +R to explore the Run Window.

Now enter the following command:

rundll32.exe sysdm.cpl,EditEnvironmentVariables

system environment variable

All these methods should open the list of all the environment variables categorized under separate sections for user and system environment variables. You can create new user variables, edit the existing ones, or delete them using the same dialogue box.

Steps to create a new environment variable

Click on the “New” option using the Environment Variables dialogue box.

Now enter the Variable Name and its Value under the respective columns and press OK.

Creating the JAVA_HOME environment variable is a crucial step for installing Java Development Kit. So, let’s create the JAVA_HOME variable and later verify its existence. Click on the New option and enter “JAVA_HOME” as the variable name. Also, enter the installation path for the JDK as the variable value for JAVA_HOME.

The JAVA_HOME variable is now visible on the list of all environment variables, with the variable value as the path to the JDK. You can verify it by going to the “edit system variable” settings, and the JAVA_HOME variable should be present right there.

Steps to Edit environment variables

Click on the environment variable you want to edit and press the “Edit” option.

Now enter the Variable Name and its Value and press the OK button.

Let’s now edit the JAVA_HOME variable that we just created and change its value to another folder. Click on the variable and select the “Edit” option. Now enter a different variable value replacing the previous value and click OK.

Here also, you can verify the changed value on the environment variable list.

The updated variable is present on the user variable list.

Steps to Delete environment variables

Click on the environment variable you want to Delete.

Now Press the “Delete” option and press OK.

As an example, let’s delete the JAVA_HOME variable that we recently tweaked. Select the variable and press “Delete” and “OK” subsequently. The selected variable gets deleted from the list of variables.

The JAVA_HOME variable gets deleted from the list.

Command Prompt Method

You can use the Command Prompt or Windows PowerShell to set up environment variables. Let’s first look at how to use the command prompt method.

Viewing the environment variables

Open the command prompt in Windows.

Now enter “set” and press Enter. You can see the entire list of environment variables without any categorization, unlike the GUI-based method.

Creating new environment variables

Open the command prompt.

Use the following syntax using the setx command and press Enter:

setx [variable_name] “[variable_value]”

[variable_name] stands for the name of the variable you want to enter.

[variable_value] stands for the value for the newly created variable.

For example, let’s create a “TEST_VARIABLE” with a value “XYZ” and then verify its existence using Command Prompt. We use the following command:

setx [TEST_VARIABLE] “[XYZ]”

Congratulations! You just created a new user variable using Command Prompt. Now, let’s verify its existence. Use the “set” command to see the list of all the variables.

Windows PowerShell Method

PowerShell gives you more flexibility with the environment variables and lets you view, edit, and create them, but these are only valid for a single PowerShell session. The variable list returns to its original form once you close a PowerShell session.

Viewing system variables

Open the Windows PowerShell.

Now enter the following command:

Get-ChildItem Env:

Windows PowerShell will display the complete list of environment variables.

The environment variables won’t get categorized under system and user variables, but you can use the following commands to only view system variables using PowerShell:

[Environment]::GetEnvironmentVariables("Machine")

Otherwise, you can use the following command to only view the user environment variables:

[Environment]::GetEnvironmentVariables("User")

Creating and Editing environment variables

You can edit and create new environment variables using the $env built-in variable. Use the following command to create a new variable using PowerShell:

$env:Variable_name = 'Variable_value'

Here Variable_name stands for the name of the newly created environment variable, and the variable_value stands for its value.

Let’s create another test variable TEST_VARIABLE as an example and then verify its existence. We use the following command in the PowerShell:

$env:TEST_VARIABLE = '[ABC]'

We have also confirmed the variable value for TEST_VARIABLE using the following code:

$env:TEST_VARIABLE

PowerShell shows the output for the TEST_VARIABLE variable as [ABC].

Moreover, you can also tweak the value for an existing environment value using the following command:

$env:Variable_name = ';Variable_value2'

This would append the newly mentioned value to the original value for the environment variable.

Conclusion 🧑‍💻

Creating and tweaking system environment variables is crucial to direct programs and utilize their functionality. Windows gives you GUI-based and Command Line options to do the same. The GUI-based methods are simple and easy to follow. On the other hand, the Command-Line methods are swifter but more complicated.

Now you may check Tuning MySQL system variables for high performance.

Переменные среды Windows 11 и Windows 10Настройка переменных среды Windows может помочь сократить время, необходимое для набора команд в командной строке или, если вы часто пишете скрипты для собственных задач, сделать их более читаемыми. В большинстве случаев обычные пользователи добавляют записи в системную переменную среды PATH, хотя бывают и другие задачи.

В этой пошаговой инструкции базовая информация о том, как открыть переменные среды Windows 11 и Windows 10, создать или отредактировать их.

Что такое переменные среды

Переменные среды в Windows — записи о расположении системных папок, свойствах системы и другие, которые доступны для любой программы или скрипта.

Одна из наиболее часто используемых переменных среды — PATH, указывающая на папки, в которых выполняется поиск файлов, вызываемых в командной строке, терминале Windows, файле bat или из других источников. В качестве примера её назначения:

  • Если вы откроете командную строку (или диалоговое окно «Выполнить»), введёте regedit и нажмете Enter — вы сможете запустить редактор реестра, не указывая полный путь к файлу regedit.exe, поскольку путь C:Windows добавлен в переменную среды Path.
  • Если же тем же образом в командной строке написать имя программы, путь к которой не добавлен в Path (chrome.exe, adb.exe, pip и другие), вы получите сообщение «Не является внутренней или внешней командой, исполняемой программой или пакетным файлом».

Если предположить, что вы часто используете команды adb.exe (например, для установки приложений Android в Windows 11), pip install (для установки пакетов Python) или любые другие то для того, чтобы не писать каждый раз полный путь к этим файлам, имеет смысл добавить эти пути в переменные среды.

Также вы можете добавлять и иные переменные среды (не обязательно содержащие пути), а в дальнейшем получать и использовать их значения в сценариях BAT (командной строки) или PowerShell. Пример получения и отображения значения системной переменной PATH для обоих случаев:

echo %PATH%
echo $Env:PATH

Получить список всех переменных среды в командной строке и PowerShell соответственно можно следующими командами:

set
ls env:

Редактирование переменных среды Windows 11/10

Прежде чем приступать, учтите: изменение системных переменных среды по умолчанию может привести к проблемам в работе системы, не удаляйте уже имеющиеся переменные среды. Возможно, имеет смысл создать точку восстановления системы, если вы не уверены в своих действиях.

  1. Чтобы открыть переменные среды Windows вы можете использовать поиск в панели задач (начните вводить «Переменных» и откройте пункт «Изменение системных переменных среды») или нажать клавиши Win+R на клавиатуре, ввести sysdm.cpl и нажать Enter. Открыть изменение переменных среды в Windows
  2. На вкладке «Дополнительно» нажмите кнопку «Переменные среды…» Переменные среды в параметрах системы Windows
  3. В разделе «Переменные среды пользователя» (если требуется изменение только для текущего пользователя) или «Системные переменные» выберите переменную, которую нужно изменить и нажмите «Изменить» (обычно требуется именно это), либо, если необходимо создать новую переменную — нажмите кнопку «Создать». В моем примере — добавляем свои пути в системную переменную Path (выбираем эту переменную и нажимаем «Изменить»). Создание и изменение переменных среды Windows
  4. Для добавления нового значения (пути) в системную переменную в следующем окне можно нажать кнопку «Создать», либо просто дважды кликнуть по первой пустой строке, затем — ввести нужный путь к папке, содержащей нужные нам исполняемые файлы. Изменение переменно PATH
  5. Также вы можете использовать кнопку «Изменить текст», в этом случае окно изменения системной переменной откроется в ином виде: имя переменной, а ниже — её значение. В случае указания путей значение будет представлять собой все пути, хранящиеся в переменной, разделенные знаком «точка с запятой». Изменение имени и значения системной переменной среды
  6. При создании новой переменной среды окно будет тем же, что и в 5-м шаге: необходимо будет указать имя системной переменной в верхнем поле, а её значение — в нижнем.

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

Environment variables are not often seen directly when using Windows. However there are cases, especially when using the command line, that setting and updating environment variables is a necessity. In this series we talk about the various approaches we can take to set them. In this article we look at how to interface with environment variables using the Command Prompt and Windows PowerShell. We also note where in the registry the environment variables are set, if you needed to access them in such a fashion.

Print environment variables

You can use environment variables in the values of other environment variables. It is then helpful to be able to see what environment variables are set already. This is how you do it:

Command Prompt

List all environment variables

Command Prompt — C:>

Output

1
2
3
4
5
6
ALLUSERSPROFILE=C:ProgramData
APPDATA=C:UsersuserAppDataRoaming
.
.
.
windir=C:Windows

Print a particular environment variable:

Command Prompt — C:>

Output

Windows PowerShell

List all environment variables

Windows PowerShell — PS C:>

Output

1
2
3
4
5
6
7
8
Name                           Value
----                           -----
ALLUSERSPROFILE                C:ProgramData
APPDATA                        C:UsersuserAppDataRoaming
.
.
.
windir                         C:Windows

Print a particular environment variable:

Windows PowerShell — PS C:>

Output

Set Environment Variables

To set persistent environment variables at the command line, we will use setx.exe. It became part of Windows as of Vista/Windows Server 2008. Prior to that, it was part of the Windows Resource Kit. If you need the Windows Resource Kit, see Resources at the bottom of the page.

setx.exe does not set the environment variable in the current command prompt, but it will be available in subsequent command prompts.

User Variables

Command Prompt — C:>

1
setx EC2_CERT "%USERPROFILE%awscert.pem"

Open a new command prompt.

Command Prompt — C:>

Output

1
C:Usersuserawscert.pem

System Variables

To edit the system variables, you’ll need an administrative command prompt. See HowTo: Open an Administrator Command Prompt in Windows to see how.

Command Prompt — C:>

1
setx EC2_HOME "%APPDATA%awsec2-api-tools" /M

Warning This method is recommended for experienced users only.

The location of the user variables in the registry is: HKEY_CURRENT_USEREnvironment. The location of the system variables in the registry is: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment.

When setting environment variables through the registry, they will not recognized immediately. One option is to log out and back in again. However, we can avoid logging out if we send a WM_SETTINGCHANGE message, which is just another line when doing this programatically, however if doing this on the command line it is not as straightforward.

One way is to get this message issued is to open the environment variables in the GUI, like we do in HowTo: Set an Environment Variable in Windows — GUI; we do not need to change anything, just open the Environment Variables window where we can see the environment variables, then hit OK.

Another way to get the message issued is to use setx, this allows everything to be done on the command line, however requires setting at least one environment variable with setx.

Printing Environment Variables

With Windows XP, the reg tool allows for accessing the registry from the command line. We can use this to look at the environment variables. This will work the same way in the command prompt or in powershell. This technique will also show the unexpanded environment variables, unlike the approaches shown for the command prompt and for powershell.

First we’ll show the user variables:

Command Prompt — C:>

1
reg query HKEY_CURRENT_USEREnvironment

Output

1
2
3
HKEY_CURRENT_USEREnvironment
    TEMP    REG_EXPAND_SZ    %USERPROFILE%AppDataLocalTemp
    TMP    REG_EXPAND_SZ    %USERPROFILE%AppDataLocalTemp

We can show a specific environment variable by adding /v then the name, in this case we’ll do TEMP:

Command Prompt — C:>

1
reg query HKEY_CURRENT_USEREnvironment /v TEMP

Output

1
2
HKEY_CURRENT_USEREnvironment
    TEMP    REG_EXPAND_SZ    %USERPROFILE%AppDataLocalTemp

Now we’ll list the system environment variables:

Command Prompt — C:>

1
reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment"

Output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment
    ComSpec    REG_EXPAND_SZ    %SystemRoot%system32cmd.exe
    FP_NO_HOST_CHECK    REG_SZ    NO
    NUMBER_OF_PROCESSORS    REG_SZ    8
    OS    REG_SZ    Windows_NT
    Path    REG_EXPAND_SZ    C:ProgramDataOracleJavajavapath;C:WINDOWSsystem32;C:WINDOWS;C:WINDOWSSystem32Wbem;C:WINDOWSSystem32WindowsPowerShellv1.0;%SystemRoot%system32;%SystemRoot%;%SystemRoot%System32Wbem;%SYSTEMROOT%System32WindowsPowerShellv1.0
    PATHEXT    REG_SZ    .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
    PROCESSOR_ARCHITECTURE    REG_SZ    AMD64
    PROCESSOR_IDENTIFIER    REG_SZ    Intel64 Family 6 Model 60 Stepping 3, GenuineIntel
    PROCESSOR_LEVEL    REG_SZ    6
    PROCESSOR_REVISION    REG_SZ    3c03
    PSModulePath    REG_EXPAND_SZ    %SystemRoot%system32WindowsPowerShellv1.0Modules;C:Program FilesIntel
    TEMP    REG_EXPAND_SZ    %SystemRoot%TEMP
    TMP    REG_EXPAND_SZ    %SystemRoot%TEMP
    USERNAME    REG_SZ    SYSTEM
    windir    REG_EXPAND_SZ    %SystemRoot%

And same as with the user variables we can query a specific variable.

Command Prompt — C:>

1
reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v PATH

Output

1
2
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment
    PATH    REG_EXPAND_SZ    C:ProgramDataOracleJavajavapath;C:WINDOWSsystem32;C:WINDOWS;C:WINDOWSSystem32Wbem;C:WINDOWSSystem32WindowsPowerShellv1.0;%SystemRoot%system32;%SystemRoot%;%SystemRoot%System32Wbem;%SYSTEMROOT%System32WindowsPowerShellv1.0

Unsetting a Variable

When setting environment variables on the command line, setx should be used because then the environment variables will be propagated appropriately. However one notable thing setx doesn’t do is unset environment variables. The reg tool can take care of that, however another setx command should be run afterwards to propagate the environment variables.

The layout for deleting a user variable is: reg delete HKEY_CURRENT_USEREnvironment /v variable_name /f. If /f had been left off, we would have been prompted: Delete the registry value EXAMPLE (Yes/No)?. For this example we’ll delete the user variable USER_EXAMPLE:

Command Prompt — C:>

1
reg delete HKEY_CURRENT_USEREnvironment /v USER_EXAMPLE /f

Output

1
The operation completed successfully.

Deleting a system variable requires administrator privileges. See HowTo: Open an Administrator Command Prompt in Windows to see how to do this.

The layout for deleting a system variable is: reg delete "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v variable_name /f. For this example we’ll delete the system variable SYSTEM_EXAMPLE:

Command Prompt — C:>

1
reg delete "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v SYSTEM_EXAMPLE /f

If this was run as a normal user you’ll get:

Output

1
ERROR: Access is denied.

But run in an administrator shell will give us:

Output

1
The operation completed successfully.

Finally we’ll have to run a setx command to propagate the environment variables. If there were other variables to set, we could just do that now. However if we were just interested in unsetting variables, we will need to have one variable left behind. In this case we’ll set a user variable named throwaway with a value of trash

Command Prompt — C:>

Output

1
SUCCESS: Specified value was saved.

Resources

  • Windows XP Service Pack 2 Support Tools
  • Windows Server 2003 Resource Kit Tools
  • Reg — Edit Registry | Windows CMD | SS64.com
  • Reg — Microsoft TechNet
  • Registry Value Types (Windows) — Microsoft Windows Dev Center
  • How to propagate environment variables to the system — Microsoft Support
  • WM_SETTINGCHANGE message (Windows) — Microsoft Windows Dev Center
  • Environment Variables (Windows) — Microsoft Windows Dev Center

Windows Server 2003 Resource Kit Tools will also work with Windows XP and Windows XP SP1; use Windows XP Service Pack 2 Support Tools with Windows XP SP2. Neither download is supported on 64-bit version.

Parts in this series

  • HowTo: Set an Environment Variable in Windows

  • HowTo: Set an Environment Variable in Windows — GUI

  • HowTo: Set an Environment Variable in Windows — Command Line and Registry

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 programming languages.

Environment Variables????

l4JA1COQqiZB6.gif

Environment variables, as the name suggests, are variables in your system that describe your environment. The most well known environment variable is probably PATH which contains the paths to all folders that might contain executables. With PATH, you can write just the name of an executable rather than the full path to it in your terminal since the shell will check the local directory as well as all directories specified in the PATH variable for this executable.

Aside from ‘built-in’ variables you also have the opportunity to define our own environment variables. Since they are bound to our environment they are great for things such as API access tokens. You could have a variable set to one value on your development machine and another in your production environment without having if-statements or special config files.

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.

Set Environment Variables on 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:

The end of the output should indicate which shell you are running. The typical shell is the bash shell which you will be using in this example. But the steps are similar for other shells like zsh or fish.

In order to set an environment variable, you need to use the export command in the following format:

Since this would only set this for the current session you need to add this command into a file that is executed for every session. For this, open the .bashrc file in your home directory with your favorite code editor. Then, add the following line somewhere in the file:

export TWILIO_ACCOUNT_SID=<YOUR_ACCOUNT_SID>

Replace <YOUR_ACCOUNT_SID> 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.

terminal-env-variable.png

Windows Environment Variables

If you’re using a Windows machine, you have a couple of ways to set environment variables. The most common methods are to use PowerShell, CMD, or the Graphical User Interface (GUI).

There are three different locations you can store environment variables:

  • In the current process. The current process is most commonly the shell you are running, like PowerShell, CMD, Bash, etc. However, the current process could also be other applications including yours. Any child process started from the current process inherits that process’ environment variables. The environment variables are removed when the process ends. This means you need to reconfigure the environment variables whenever you open a new shell.
    This is also how environment variables are stored on macOS and Linux distributions.
  • In the user registry. The environment variable is available to all processes started by the user, and no other users can access those environment variables (without elevated privileges).
  • In the machine registry. The environment variables are available to all users and processes, and setting environment variables for the machine requires elevated privileges.

Changes made to user and machine environment variables aren’t available to processes that are already running. For the change to apply, restart your program or shell, or set the environment variable for both the process and the user or machine.

In which location should you store the environment variables?

If you’re running your application from a shell and don’t want the environment variables to stick around, set the environment variables for the current process. If you do want the environment variables to stick around, store them in the user registry. If you want to configure environment variables for all users, not just for a specific user or yourself, then store them in the machine registry.

Set Environment Variables using PowerShell

While PowerShell is also supported on macOS and Linux distributions through PowerShell Core, Windows PowerShell is preinstalled on Windows and is the recommended shell for the Windows platform. The following cmdlets for configuring environment variables will work on Windows, macOS, and Linux.

The most common and easiest way to set environment variables in PowerShell is to use the $Env variable, like this:

$Env:TWILIO_ACCOUNT_SID = '<YOUR_ACCOUNT_SID>'

After $Env, add a colon, followed by the environment variable’s name, followed by the equals sign, followed by the value you want to use. This will set the environment variable for the current process, and will be inherited by any child process you start from this shell.

The following two alternatives have the same result, but are less common:

New-Item -Path Env:TWILIO_ACCOUNT_SID -Value '<YOUR_ACCOUNT_SID>'
[Environment]::SetEnvironmentVariable('TWILIO_ACCOUNT_SID', '<YOUR_ACCOUNT_SID>')
[Environment]::SetEnvironmentVariable('TWILIO_ACCOUNT_SID', '<YOUR_ACCOUNT_SID>', 'Process')

To persist environment variables across shell instances, you can save the cmdlets into your profile script, or on Windows, you can save them in the user registry or machine registry like this:

[Environment]::SetEnvironmentVariable('TWILIO_ACCOUNT_SID', '<YOUR_ACCOUNT_SID>', 'User')
# requires elevated shell
[Environment]::SetEnvironmentVariable('TWILIO_ACCOUNT_SID', '<YOUR_ACCOUNT_SID>', 'Machine')

Setting environment variables in the user and/or machine registry will not immediately update the environment variables for processes that are currently running. To see the effects of the update environment variables, you’ll need to restart those processes, such as your PowerShell shell.

The two commands above result in a no-op on macOS and Linux because there’s no concept of User or Machine environment variables, only process environment variables. Consult the Microsoft documentation on PowerShell environment variables for more details.

Set Environment Variables from CMD

Cmd, otherwise known as cmd.exe and the Command Prompt also comes with all installations of Windows. You should probably use PowerShell, but if you can’t, here’s how you can set environment variables from cmd and batch files.

To set an environment variable you can use the set command, like this:

set TWILIO_ACCOUNT_SID=<YOUR_ACCOUNT_SID>

This command will set the environment variable for the current process, and child processes will inherit the environment variables. However, when you close cmd the environment variables will be lost.

To persist the environment variables across processes, you can store them in the user and/or machine registry using the setx command.

# sets environment variable in the user registry
setx TWILIO_ACCOUNT_SID <YOUR_ACCOUNT_SID>

# sets environment variable in the machine registry
setx TWILIO_ACCOUNT_SID <YOUR_ACCOUNT_SID> /m

Setting environment variables in the user and/or machine registry will not immediately update the environment variables for processes that are currently running. To see the effects of the update environment variables, you’ll need to restart those processes, like your PowerShell shell.

These commands have more capabilities which you can dig into by reading the set command and setx command docs.

Set Environment Variables using the Graphical User Interface

Setting environment variables in Windows using the GUI is hidden behind several layers of settings dialogs. To open the respective interface you first have to open the Windows Run prompt. Do so by pressing the Windows and R keys on your keyboard at the same time. Then, type sysdm.cpl into the input field and hit Enter or press Ok.

run-dialog.png

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.

windows-advanced-dialog.pngwindows-env-dialog.png

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.

new-dialog.png

To test if it worked open the Command Prompt by pressing Windows + R and typing cmd.exe. If you have the Command Prompt open already, make sure to restart it to ensure your changes are applied. Inside the Command Prompt execute the following command:

echo %TWILIO_ACCOUNT_SID%

This should print the value that you saved in the environment variable.

windows-cmd-dialog.png

Use .env files

In some situations you only need an environment variable set for only a single project. In that case .env files are a great solution. They’re files inside your project in which you specify environment variables and afterwards you use a library for your respective programming language to load the file which will dynamically define these variables.

There are libraries for most programming languages to load these files. Here are a few:

  • Ruby
  • Node.js
  • Python
  • C#, F#, VB.NET (dotnet-env or dotenv.net)
  • Java (tutorial)
  • PHP

Create a .env file in your project folder (typically at the root) and place the key value pairs in there. This can look like this:

TWILIO_ACCOUNT_SID=<YOUR_ACCOUNT_SID>

Now all you need to do is consume the respective library and then you can use the environment variable. In Node.js, for example, the respective code would look like this:

require('dotenv').config();
console.log('Your environment variable TWILIO_ACCOUNT_SID has the value: ', process.env.TWILIO_ACCOUNT_SID);

Since you most likely don’t want to commit your environment variables to a repository, make sure to add the .env file to your .gitignore to avoid accidentally pushing it.

Cloud Providers

Setting environment variables on your local development machine or in a VM is only half the work. What if you are hosting your application in a cloud environment such as Heroku, Azure, or AWS, or you’ve wrapped it in a Docker container? Luckily, all of these providers support ways to define environment variables.

  • Heroku
  • Azure (App Service, Functions, Container Instances)
  • AWS
  • Dockerfile
  • Docker Run

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.

If you have any questions or would like to show me the awesome thing you are currently building, feel free to send me an email to: dkundel@twilio.com or contact me on Twitter @dkundel. I can’t wait to see what you build.

Понравилась статья? Поделить с друзьями:
  • Windows servicing packages что это за папка
  • Windows serviceprofiles networkservice appdata local microsoft windows delivery optimization cache
  • Windows service volume shadow copy service
  • Windows service the system cannot find the file specified
  • Windows service started and then stopped