- HowTo: Set an Environment Variable in Windows — Command Line and Registry
- Print environment variables
- Command Prompt
- Command Prompt — C:\>
- Output
- Command Prompt — C:\>
- Output
- Windows PowerShell
- Windows PowerShell — PS C:\>
- Output
- Windows PowerShell — PS C:\>
- Output
- Set Environment Variables
- User Variables
- Command Prompt — C:\>
- Command Prompt — C:\>
- Output
- System Variables
- Command Prompt — C:\>
- Registry
- Printing Environment Variables
- Set (переменная среды) set (environment variable)
- Синтаксис Syntax
- Параметры Parameters
- Комментарии Remarks
- Примеры Examples
- Set env var windows
- Display a variable:
- Set a variable:
- Values with Spaces — using Double Quotes
- Variable names with spaces
- Prompt for user input
- Place the first line of a file into a variable:
- Arithmetic expressions (SET /a)
- Leading Zero will specify Octal
- Permanent changes
- Change the environment for other sessions
- CALL SET
- Autoexec.bat
- Errorlevels
HowTo: Set an Environment Variable in Windows — Command Line and Registry
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
Print a particular environment variable:
Command Prompt — C:\>
Output
Windows PowerShell
List all environment variables
Windows PowerShell — PS C:\>
Output
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:\>
Open a new command prompt.
Command Prompt — C:\>
Output
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:\>
Registry
The location of the user variables in the registry is: HKEY_CURRENT_USER\ Environment . The location of the system variables in the registry is: HKEY_LOCAL_MACHINE\ SYSTEM\ CurrentControlSet\ Control\ Session Manager\ Environment .
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.
Set (переменная среды) set (environment variable)
Отображает, устанавливает или удаляет переменные среды cmd.exe. Displays, sets, or removes cmd.exe environment variables. Если используется без параметров, Set отображает текущие параметры переменной среды. If used without parameters, set displays the current environment variable settings.
Для этой команды требуются расширения команд, которые включены по умолчанию. This command requires command extensions, which are enabled by default.
Команда Set также может запускаться из консоли восстановления Windows с использованием различных параметров. The set command can also run from the Windows Recovery Console, using different parameters. Дополнительные сведения см. в разделе Среда восстановления Windows (WinRE). For more information, see Windows Recovery Environment (WinRE).
Синтаксис Syntax
Параметры Parameters
Параметр Parameter | Описание: Description |
---|---|
Задает переменную среды, которую необходимо задать или изменить. Specifies the environment variable to set or modify. | |
Указывает строку, связываемую с указанной переменной среды. Specifies the string to associate with the specified environment variable. | |
/p /p | Присваивает значение строке ввода, введенному пользователем. Sets the value of to a line of input entered by the user. |
Указывает сообщение, предлагающее пользователю ввести данные. Specifies a message to prompt the user for input. Этот параметр должен использоваться с параметром /p . This parameter must be used with the /p parameter. | |
/a /a | Задает числовое выражение, которое вычисляется. Sets to a numerical expression that is evaluated. |
Задает числовое выражение. Specifies a numerical expression. | |
/? /? | Отображение справки в командной строке. Displays help at the command prompt. |
Комментарии Remarks
Если расширения команд включены (по умолчанию) и вы запускаете Set со значением, отображаются все переменные, которые начинаются с этого значения. If command extensions are enabled (the default) and you run set with a value, it displays all of the variables that begin with that value.
Символы ,, > , | & и ^ являются специальными символами командной оболочки и перед ними должны начинаться escape-символом ( ^ ) или заключены в кавычки (например , «стрингконтаининг&Symbol»). The characters , > , | , & , and ^ are special command shell characters, and they must be preceded by the escape character ( ^ ) or enclosed in quotation marks when used in (for example, «StringContaining&Symbol»). Если строка, содержащая специальный символ, заключена в кавычки, кавычки необходимо указывать как часть значения переменной среды. If you use quotation marks to enclose a string that contains one of the special characters, the quotation marks are set as part of the environment variable value.
Используйте переменные среды для управления поведением некоторых пакетных файлов и программ, а также для управления отображением окон и подсистемы MS-DOS. Use environment variables to control the behavior of some batch files and programs and to control the way Windows and the MS-DOS subsystem appears and works. Команда Set часто используется в файле Autoexec. NT для задания переменных среды. The set command is often used in the Autoexec.nt file to set environment variables.
Если вы используете команду Set без параметров, отображаются текущие параметры среды. If you use the set command without any parameters, the current environment settings are displayed. Эти параметры обычно включают переменные среды ComSpec и path , которые используются для поиска программ на диске. These settings usually include the COMSPEC and PATH environment variables, which are used to help find programs on disk. В Windows используются две другие переменные среды: Prompt и DIRCMD. Two other environment variables used by Windows are PROMPT and DIRCMD.
Если заданы значения для и , указанное значение добавляется в среду и связывается с этой переменной. If you specify values for and , the specified value is added to the environment and is associated with that variable. Если переменная уже существует в среде, новое строковое значение заменяет старое. If the variable already exists in the environment, the new string value replaces the old string value.
Если указать только переменную и знак равенства (без ) для команды Set , значение, связанное с переменной, будет очищаться (как если бы переменная отсутствует). If you specify only a variable and an equal sign (without ) for the set command, the value associated with the variable is cleared (as if the variable is not there).
При использовании параметра /a поддерживаются следующие операторы в порядке убывания приоритета. If you use the /a parameter, the following operators are supported, in descending order of precedence:
Оператор Operator | Выполненная операция Operation performed |
---|---|
( ) | Группирование Grouping |
! — | Унарный Unary |
* / % | Арифметические Arithmetic |
+ — | Арифметические Arithmetic |
> | Логическая смена Logical shift |
& | Побитовое И Bitwise AND |
^ | Побитовое исключающее ИЛИ Bitwise exclusive OR |
= *= /= %= += -= &= ^= | = >= |
, | Разделитель выражений Expression separator |
Если используются операторы логического ( && или || ) или модуля ( % ), заключите строку выражения в кавычки. 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.
При запуске set/a из командной строки за пределами командного скрипта отображается конечное значение выражения. If you run set /a from the command line outside of a command script, it displays the final value of the expression.
Числовые значения — это десятичные числа, кроме префикса 0 × для шестнадцатеричных чисел или 0. Numeric values are decimal numbers unless prefixed by 0× for hexadecimal numbers or 0 for octal numbers. Таким образом, 0 × 12 совпадает с 18, что совпадает с 022. Therefore, 0×12 is the same as 18, which is the same as 022.
Отложенная поддержка расширения переменных среды по умолчанию отключена, но ее можно включить или отключить с помощью команды cmd/v. Delayed environment variable expansion support is disabled by default, but you can enable or disable it by using cmd /v.
При создании пакетных файлов можно использовать команду Set для создания переменных, а затем использовать их так же, как и пронумерованные переменные %0 – %9. 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. Можно также использовать переменные %0 – %9 в качестве входных данных для Set. 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
Чтобы задать значение Test ^ 1 для переменной среды с именем testVar , введите: To set the value TEST^1 for the environment variable named testVar , type:
Команда Set назначает значение переменной всем, что следует за знаком равенства (=). The set command assigns everything that follows the equal sign (=) to the value of the variable. Поэтому при вводе set testVar=test^1 вы получите следующий результат: testVar=test^1 . Therefore, if you type set testVar=test^1 , you’ll get the following result, testVar=test^1 .
Чтобы задать значение TEST&1 для переменной среды testVar , введите: To set the value TEST&1 for the environment variable testVar , type:
Чтобы задать переменную среды с именем include , с которой связана строка к:\директори , введите: 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 (%). Например, можно использовать dir %include% в пакетном файле для вывода содержимого каталога, связанного с переменной среды include. For example, you can use dir %include% in a batch file to display the contents of the directory associated with the INCLUDE environment variable. После обработки этой команды строка к:\директори заменяет % include%. After this command is processed, the string c:\directory replaces %include%.
Чтобы использовать команду Set в пакетной программе для добавления нового каталога в переменную среды path , введите: To use the set command in a batch program to add a new directory to the PATH environment variable, type:
Чтобы отобразить список всех переменных среды, начинающихся с буквы P, введите: To display a list of all of the environment variables that begin with the letter P, type:
Set env var windows
Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.
Variable names are not case sensitive but the contents can be.
It is good practice to avoid using any delimiter characters (spaces, commas etc) in the variable name.
Delimiter characters can be used in the value if the complete assignment is surrounded with double quotes to prevent the delimiter being interpreted.
Any extra spaces around either the variable name or the string, will not be ignored, SET is not forgiving of extra spaces like many other scripting languages. So use SET alpha=beta , not SET alpha = beta
The first character of the name must not be numeric. It is a common practice to prefix variable names with either an undescore or a dollar sign _variable or $variable , these prefixes are not required but help to prevent any confusion with the standard built-in Windows Environment variables or any other other command strings.
The CMD shell will fail to read an environment variable if it contains more than 8,191 characters.
Display a variable:
In most contexts, surround the variable name with % ‘s and the variable’s value will be used
e.g. To display the value of the _department variable with the ECHO command:
ECHO %_department%
If the variable name is not found in the current environment then SET will set %ERRORLEVEL% to 1 .
This can be detected using IF ERRORLEVEL .
Including extra characters can be useful to show any white space:
ECHO [%_department% ]
ECHO «%_department% »
Type SET without parameters to display all the current environment variables.
Type SET with a variable name to display that variable
SET _department
The SET command invoked with a string (and no equal sign) will display a wildcard list of all matching variables
Display variables that begin with ‘P’:
SET p
Display variables that begin with an underscore
SET _
Set a variable:
Example of storing a text string:
C:\> SET _dept=Sales and Marketing
C:\> set _
_dept=Sales and Marketing
Set a variable that contains a redirection character, note the position of the quotes which are not saved:
SET «_dept=Sales & Marketing»
One variable can be based on another, but this is not dynamic
E.g.
C:\> set «xx=fish»
C:\> set «msg=%xx% chips»
C:\> set msg
msg=fish chips
C:\> set «xx=sausage»
C:\> set msg
msg=fish chips
C:\> set «msg=%xx% chips»
C:\> set msg
msg=sausage chips
Avoid starting variable names with a number, this will avoid the variable being mis-interpreted as a parameter
%123_myvar% %1 23_myvar
To display undocumented system variables:
Values with Spaces — using Double Quotes
Although it is advisable, there is no requirement to add quotation marks when assigning a value that includes spaces:
SET _variable=one two three
For special characters like & surround the entire expression with quotation marks.
The variable contents will not include the surrounding quotes:
n.b. if you only place quotation marks around the value, then those quotes will be stored:
Variable names with spaces
A variable can contain spaces and also the variable name itself can contain spaces, therefore the following assignment:
SET _var =MyText
will create a variable called «_var » — note the trailing space
Prompt for user input
The /P switch allows you to set a variable equal to a line of input entered by the user.
The Prompt string is displayed before the user input is read.
The Prompt string can be empty. The variable name can also be left empty but this is undocumented.
If the user does not enter anything (just presses return) then the variable will be unchanged and an errorlevel will be set to 1.
The CHOICE command is an alternative to SET /P (but CHOICE accepts only one character/keypress.)
Place the first line of a file into a variable:
Better still, to be sure there is no trailing space after the = place the expression in parentheses or quotes:
(SET _department=)
or
SET «_department=»
Arithmetic expressions (SET /a)
Placing expressions in «quotes» is optional for simple arithmetic but required for any expression using logical operators.
When refering to a variable in your expression, SET /A allows you to omit the %’s so _myvar instead of %_myvar%
Any SET /A calculation that returns a fractional result will be rounded down to the nearest whole integer.
The expression to be evaluated can include the following operators:
For the Modulus operator use (%) on the command line, or in a batch script it must be doubled up to (%%) as below.
This is to distinguish it from a FOR parameter.
If a variable name is specified as part of the expression, but is not defined in the current environment, then SET /a will use a value of 0.
SET /A arithmetic shift operators do not detect overflow which can cause problems for any non-trivial math, e.g. the bitwise invert often incorrectly reverses the + / — sign of the result.
See SET /a examples below and this forum thread for more.
also see SetX, VarSearch and VarSubstring for more on variable manipulation.
SET /A should work within the full range of 32 bit signed integer numbers (-2,147,483,648 through 2,147,483,647) but in practice for negative integers it will not go below -2,147,483,647
SET /A «_result=2+4»
(=6)
SET /A «_result=2 SET /A «_result=5 + _MyVar «
Multiple calculations can be performed in one line, by separating each calculation with commas, for example:
Set «_year=1999»
Set /a «_century=_year/100, _next=_century+1»
The numbers must all be within the range of 32 bit signed integer numbers (-2,147,483,648 through 2,147,483,647) to handle larger numbers use PowerShell or VBScript.
Leading Zero will specify Octal
Numeric values are decimal numbers, unless prefixed by
0x for hexadecimal numbers,
0 for octal numbers.
So 0x10 = 020 = 16 decimal
The octal notation can be confusing — all numeric values that start with zeros are treated as octal but 08 and 09 are not valid octal digits.
For example SET /a «_month=07 » will return the value 7, but SET /a «_month=09» will return an error.
Permanent changes
Changes made using the SET command are NOT permanent, they apply to the current CMD prompt only and remain only until the CMD window is closed.
To permanently change a variable at the command line use SetX
or with the GUI — Control Panel | System | Environment | System/User Variables
Changing a variable permanently with SetX will not affect any CMD prompt that is already open.
Only new CMD prompts will get the new setting.
You can of course use SetX in conjunction with SET to change both at the same time:
Set _Library=T:\Library\
SetX _Library T:\Library\ /m
Change the environment for other sessions
Neither SET nor SetX will affect other CMD sessions that are already running on the machine . This as a good thing, particularly on multi-user machines, your scripts won’t have to contend with a dynamically changing environment while they are running.
It is possible to add permanent environment variables to the registry ( HKCU\Environment ), but this is an undocumented (and likely unsupported) technique and still it will not take effect until the users next login.
System environment variables can be found in the registry here:
HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
CALL SET
The CALL SET syntax allows a variable substring to be evaluated, the CALL page has more detail on this technique, in most cases a better approach is to use Setlocal EnableDelayedExpansion
Autoexec.bat
Any SET statement in c:\autoexec.bat will be parsed at boot time
Variables set in this way are not available to 32 bit gui programs — they won’t appear in the control panel.
They will appear at the CMD prompt.
If autoexec.bat CALLS any secondary batch files, the additional batch files will NOT be parsed at boot.
This behaviour can be useful on a dual boot PC.
Errorlevels
If the variable was successfully changed | unchanged , typically this will be 0 but if a previous command set an errorlevel, that will be preserved (this is a bug). |
SET No variable found or invalid name. SET _var=value when _var name starts with «/» and not enclosed in quotes. SET /P Empty response from user. | 1 |
SET /A Unbalanced parentheses | 1073750988 |
SET /A Missing operand | 1073750989 |
SET /A Syntax error | 1073750990 |
SET /A Invalid number | 1073750991 |
SET /A Number larger than 32-bits | 1073750992 |
SET /A Division by zero | 1073750993 |
SET is an internal command.
If Command Extensions are disabled all SET commands are disabled other than simple assignments like: _variable=MyText
# I got my mind set on you
# I got my mind set on you. — Rudy Clark (James Ray/George Harrison)
Syntax — VarSubstring Extract part of a variable (substring).
Syntax — VarSearch Search & replace part of a variable.
Syntax — Environment Variables — List of default variables.
CALL — Evaluate environment variables.
ENDLOCAL — End localisation of environment changes, use to return values.
EXIT — Set a specific ERRORLEVEL.
PATH — Display or set a search path for executable files.
REG — Read or Set Registry values.
SETLOCAL — Begin localisation of environment variable changes.
SETX — Set an environment variable permanently.
WMIC ENVIRONMENT — Set environment variables through WMI.
Parameters — get a full or partial pathname from a command line variable.
StackOverflow — Storing a Newline in a variable.
Powershell: Set-Variable — Set a variable and a value (set/sv).
Powershell: Read-Host — Prompt for user input.
Equivalent bash command (Linux): env — Display, set, or remove environment variables.