Windows set environment variable from command line

set (environment variable)

Displays, sets, or removes cmd.exe environment variables. If used without parameters, set displays the current environment variable settings.

This command requires command extensions, which are enabled by default.

The set command can also run from the Windows Recovery Console, using different parameters. For more information, see Windows Recovery Environment (WinRE).

Syntax

Parameters

ParameterDescription
Specifies the environment variable to set or modify.
Specifies the string to associate with the specified environment variable.
/pSets the value of to a line of input entered by the user.
Specifies a message to prompt the user for input. This parameter must be used with the /p parameter.
/aSets to a numerical expression that is evaluated.
Specifies a numerical expression.
/?Displays help at the command prompt.

Remarks

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.

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. The set command is often used in the Autoexec.nt file to set environment variables.

If you use the set command without any parameters, the current environment settings are displayed. These settings usually include the COMSPEC and PATH environment variables, which are used to help find programs on disk. Two other environment variables used by Windows are PROMPT and DIRCMD.

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).

If you use the /a parameter, the following operators are supported, in descending order of precedence:

OperatorOperation performed
( )Grouping
!

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:

Источник

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

Комментарии 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.

Используйте переменные среды для управления поведением некоторых пакетных файлов и программ, а также для управления отображением окон и подсистемы 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.

При использовании параметра /a поддерживаются следующие операторы в порядке убывания приоритета. If you use the /a parameter, the following operators are supported, in descending order of precedence:

Параметр 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.
Оператор OperatorВыполненная операция Operation performed
( )Группирование Grouping
!

Если используются операторы логического ( && или || ) или модуля ( % ), заключите строку выражения в кавычки. 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.

Примеры Examples

Затем можно использовать строку к:\директори в пакетных файлах, заключив имя в символы процента ( % ). 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%.

Чтобы отобразить список всех переменных среды, начинающихся с буквы P, введите: To display a list of all of the environment variables that begin with the letter P, type:

Источник

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

1\Java\jdk1.7.0_09″ – samael Jul 31 ’13 at 10:01

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_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment» /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.

Windows set environment variable from command line. Смотреть фото Windows set environment variable from command line. Смотреть картинку Windows set environment variable from command line. Картинка про Windows set environment variable from command line. Фото Windows set environment variable from command line

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

Источник

Windows set environment variable from command line

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.

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%

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:

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

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.

See SET /a examples below and this forum thread for more.
also see SetX, VarSearch and VarSubstring for more on variable manipulation.

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

Permanent changes

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

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

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

SET is an internal command.
If Command Extensions are disabled all SET commands are disabled other than simple assignments like: _variable=MyText

Источник

Переменные среды в 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 set environment variable from command line. Смотреть фото Windows set environment variable from command line. Смотреть картинку Windows set environment variable from command line. Картинка про Windows set environment variable from command line. Фото Windows set environment variable from command line

Windows set environment variable from command line. Смотреть фото Windows set environment variable from command line. Смотреть картинку Windows set environment variable from command line. Картинка про Windows set environment variable from command line. Фото Windows set environment variable from command line

Доступ к переменным средам из реестра Windows

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

Системные переменные среды находятся по следующему пути:

Windows set environment variable from command line. Смотреть фото Windows set environment variable from command line. Смотреть картинку Windows set environment variable from command line. Картинка про Windows set environment variable from command line. Фото Windows set environment variable from command line

Переменные среды локального пользователя расположены в следующей ветке реестра:

Windows set environment variable from command line. Смотреть фото Windows set environment variable from command line. Смотреть картинку Windows set environment variable from command line. Картинка про Windows set environment variable from command line. Фото Windows set environment variable from command line

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

Как посмотреть все переменные среды в командной строке

Пользователь может получить список переменных среды при помощи системного инструмента — командной строки Windows.

В cmd переменные среды открываются следующим образом:

Windows set environment variable from command line. Смотреть фото Windows set environment variable from command line. Смотреть картинку Windows set environment variable from command line. Картинка про Windows set environment variable from command line. Фото Windows set environment variable from command line

Для получения списка переменных в виде текстового файла, выполните в командной строке команду:

После выполнения этой команды, на Локальном диске «C:» появится текстовый файл с именем «Variables» (имя можно использовать любое), в котором находится список переменных среды Windows.

На моем компьютере файл имеет следующее содержание:

Открытие списка переменных среды в Windows PowerShell

Открытие списка переменных среды возможно при помощи системного средства Windows PowerShell.

Выполните следующие действия:

Windows set environment variable from command line. Смотреть фото Windows set environment variable from command line. Смотреть картинку Windows set environment variable from command line. Картинка про Windows set environment variable from command line. Фото Windows set environment variable from command line

Создание переменной среды в Windows

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

Windows set environment variable from command line. Смотреть фото Windows set environment variable from command line. Смотреть картинку Windows set environment variable from command line. Картинка про Windows set environment variable from command line. Фото Windows set environment variable from command line

На этом примере я создам отдельную переменную среды для запуска программы TeamViewer.

Windows set environment variable from command line. Смотреть фото Windows set environment variable from command line. Смотреть картинку Windows set environment variable from command line. Картинка про Windows set environment variable from command line. Фото Windows set environment variable from command line

Windows set environment variable from command line. Смотреть фото Windows set environment variable from command line. Смотреть картинку Windows set environment variable from command line. Картинка про Windows set environment variable from command line. Фото Windows set environment variable from command line

Windows set environment variable from command line. Смотреть фото Windows set environment variable from command line. Смотреть картинку Windows set environment variable from command line. Картинка про Windows set environment variable from command line. Фото Windows set environment variable from command line

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

Переменная среды пути «Path» содержит список директорий на компьютере, в которых система должна искать исполняемые файлы. Переменная среды пути «PATH» не добавляется к исполняемым файлам, а только к директориям, где находятся данные файлы.

Windows set environment variable from command line. Смотреть фото Windows set environment variable from command line. Смотреть картинку Windows set environment variable from command line. Картинка про Windows set environment variable from command line. Фото Windows set environment variable from command line

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

Список переменных среды Windows в таблице

Для удобства посетителей сайта я собрал в общую таблицу переменные, их описание и значения в операционной системе Windows. В подавляющем большинстве случаев, системная папка расположена на диске «C:», поэтому пути в значениях даны для этого диска.

Выводы статьи

Переменные окружения Windows позволяют пользователю экономить время во время работы на компьютере. Переменными средами Windows могут пользоваться обычные пользователи или системные администраторы для быстрого доступа к объектам операционной системы, чтобы открыть нужную директорию на компьютере, или запустить программу.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *