Меню Рубрики

Set windows environment variable from command line

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 the Path and Environment Variables for Command-Line Builds

Для программ сборки из командной строки Microsoft C++ (MSVC) требуется несколько переменных среды, соответствующим образом настроенных для конфигурации установки и сборки. The Microsoft C++ (MSVC) command-line build tools require several environment variables that are customized for your installation and build configuration. Когда установщик Visual Studio устанавливает рабочую нагрузку C++, он создает настраиваемые командные файлы, или пакетные файлы, которые задают необходимые переменные среды. When a C++ workload is installed by the Visual Studio installer, it creates customized command files, or batch files, that set the required environment variables. Затем установщик использует эти командные файлы для создания ярлыков в меню «Пуск» Windows, позволяющих открыть окно командной строки разработчика. The installer then uses these command files to create shortcuts for the Windows Start menu to open a developer command prompt window. С помощью ярлыков настраиваются переменные среды для конкретной конфигурации сборки. These shortcuts set up the environment variables for a specific build configuration. Если необходимо использовать программы командной строки, можно выбрать один из этих ярлыков или открыть простое окно командной строки, а затем запустить один из настраиваемых командных файлов, чтобы задать среду конфигурации сборки самостоятельно. When you want to use the command-line tools, you can run one of these shortcuts, or you can open a plain command prompt window and then run one of the custom command files to set the build configuration environment yourself. Дополнительные сведения см. в статье Использование набора инструментов MSVC из командной строки. For more information, see Use the MSVC toolset from the command line. Сведения об использовании командных файлов с простой командной строкой см. в разделе Расположение командных файлов разработчика. To use the command files with a plain command prompt, see the section entitled Developer command file locations.

Программы командной строки MSVC используют переменные среды PATH, TMP, INCLUDE, LIB и LIBPATH, а также другие переменные среды, связанные с установленными средствами, платформами и пакетами SDK. The MSVC command-line tools use the PATH, TMP, INCLUDE, LIB, and LIBPATH environment variables, and also use other environment variables specific to your installed tools, platforms, and SDKs. Даже при простой установке Visual Studio могут задаваться двадцать и более переменных среды. Even a simple Visual Studio installation may set twenty or more environment variables. Так как значения этих переменных среды зависят от установки и выбранной конфигурации сборки и могут меняться при обновлении продукта, мы настоятельно рекомендуем использовать для их задания ярлык на окно командной строки разработчика или один из настроенных командных файлов вместо того, чтобы настраивать их самостоятельно в среде Windows. Because the values of these environment variables are specific to your installation and your choice of build configuration, and can be changed by product updates or upgrades, we strongly recommend that you use a developer command prompt shortcut or one of the customized command files to set them, instead of setting them in the Windows environment yourself.

Чтобы узнать, какие переменные среды задаются ярлыком командной строки разработчика, можно использовать команду SET. To see which environment variables are set by a developer command prompt shortcut, you can use the SET command. Откройте простое окно командной строки и сохраните выходные данные команды SET в качестве основы. Open a plain command prompt window and capture the output of the SET command for a baseline. Откройте окно командной строки разработчика и сохраните выходные данные команды SET для сравнения. Open a developer command prompt window and capture the output of the SET command for comparison. Для сравнения переменных среды и определения значений, задаваемых командной строкой разработчика, можно прибегнуть к средству сравнения, например встроенному в интегрированную среду разработки Visual Studio. A diff tool such as the one built into the Visual Studio IDE can be useful to compare the environment variables and see what is set by the developer command prompt. Сведения о переменных среды, используемых компилятором и компоновщиком, см. в статье Переменные среды CL. For information about the specific environment variables used by the compiler and linker, see CL Environment Variables.

Некоторые программы командной строки и параметры могут требовать разрешений администратора. Several command-line tools or tool options may require Administrator permission. Если при их использовании возникают проблемы с разрешениями, мы рекомендуем открыть окно командной строки разработчика с помощью команды Запуск от имени администратора. If you have permission issues when you use them, we recommend that you open the developer command prompt window by using the Run as Administrator option. В Windows 10 откройте контекстное меню для окна командной строки, а затем выберите команду Дополнительно > Запуск от имени администратора. On Windows 10, right-click to open the shortcut menu for the command prompt window, then choose More, Run as administrator.

Источник

setx setx

Создает или изменяет переменные среды в пользовательской или системной среде без необходимости программирования или написания сценариев. Creates or modifies environment variables in the user or system environment, without requiring programming or scripting. Команда Setx также извлекает значения разделов реестра и записывает их в текстовые файлы. The Setx command also retrieves the values of registry keys and writes them to text files.

Эта команда предоставляет единственную командную строку или программный способ для прямого и окончательного задания значений системной среды. This command provides the only command-line or programmatic way to directly and permanently set system environment values. Системные переменные среды можно настраивать вручную с помощью панели управления или редактора реестра. System environment variables are manually configurable through Control Panel or through a registry editor. Команда Set , которая является внутренней для интерпретатора команд (Cmd.exe), устанавливает переменные среды пользователя только для текущего окна консоли. The set command, which is internal to the command interpreter (Cmd.exe), sets user environment variables for the current console window only.

Синтаксис Syntax

Параметры Parameters

Параметр Parameter Описание Description
ключ /s Указывает имя или IP-адрес удаленного компьютера. Specifies the name or IP address of a remote computer. Не используйте обратные косые черты. Do not use backslashes. Значение по умолчанию — имя локального компьютера. The default value is the name of the local computer.
/u [ \] /u [ \] Запускает скрипт с учетными данными указанной учетной записи пользователя. Runs the script with the credentials of the specified user account. Значение по умолчанию — системные разрешения. The default value is the system permissions.
/p [

] Указывает пароль учетной записи пользователя, указанной в параметре /u . Specifies the password of the user account that is specified in the /u parameter. Задает имя переменной среды, которую необходимо задать. Specifies the name of the environment variable that you want to set. Задает значение, для которого необходимо задать переменную среды. Specifies the value to which you want to set the environment variable. /k

Указывает, что переменная задается на основе сведений из раздела реестра. Specifies that the variable is set based on information from a registry key. Путь использует следующий синтаксис: \\ \ \. \ . The path uses the following syntax: \\ \ \. \ . Например, можно указать следующий путь: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TimeZoneInformation\StandardName For example, you might specify the following path: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TimeZoneInformation\StandardName /f /f Указывает файл, который вы хотите использовать. Specifies the file that you want to use. / , /a , Задает абсолютные координаты и смещение в качестве параметров поиска. Specifies absolute coordinates and offset as search parameters. /r , /r , Задает относительные координаты и смещение от строки в качестве параметров поиска. Specifies relative coordinates and offset from String as search parameters. /m /m Указывает, что переменная должна быть задана в системной среде. Specifies to set the variable in the system environment. Значение по умолчанию — локальная среда. The default setting is the local environment. /x /x Отображает координаты файлов, игнорируя параметры командной строки /a, /rи /d . Displays file coordinates, ignoring the /a, /r, and /d command-line options. /d /d Указывает разделители, такие как , или, \ для использования в дополнение к четырем встроенным разделителям — пробел, табуляция, ввод и перевод строки. Specifies delimiters such as , or \ to be used in addition to the four built-in delimiters — SPACE, TAB, ENTER, and LINEFEED. Допустимые разделители включают любой символ ASCII. Valid delimiters include any ASCII character. Максимальное число разделителей равно 15, включая встроенные разделители. The maximum number of delimiters is 15, including built-in delimiters. /? /? Отображение справки в командной строке. Displays help at the command prompt.

Remarks Remarks

Эта команда аналогична служебной программе UNIX SETENV. This command is similar to the UNIX utility SETENV.

С помощью этой команды можно задать значения для переменных среды пользователя и системы в одном из трех источников (режимов): режим командной строки, режим реестра или файловый режим. You can use this command to set values for user and system environment variables from one of three sources (modes): Command Line Mode, Registry Mode, or File Mode.

Эта команда записывает переменные в главную среду в реестре. This command writes variables to the master environment in the registry. Переменные, заданные с помощью переменных Setx , доступны только в окнах командной строки в будущем, а не в текущем командном окне. Variables set with setx variables are available in future command windows only, not in the current command window.

Единственными поддерживаемыми Hive являются HKEY_CURRENT_USER и HKEY_LOCAL_MACHINE . HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE are the only supported hives. REG_DWORD, REG_EXPAND_SZ, REG_SZ и REG_MULTI_SZ являются допустимыми типами данных RegKey . REG_DWORD, REG_EXPAND_SZ, REG_SZ, and REG_MULTI_SZ are the valid RegKey data types.

Если вы получаете доступ к REG_MULTI_SZ значениям в реестре, извлекается и используется только первый элемент. If you gain access to REG_MULTI_SZ values in the registry, only the first item is extracted and used.

Эту команду нельзя использовать для удаления значений, добавленных в локальную или системную среду. You can’t use this command to remove values added to the local or system environments. Эту команду можно использовать с именем переменной и без значения, чтобы удалить соответствующее значение из локальной среды. You can use this command with a variable name and no value to remove a corresponding value from the local environment.

REG_DWORD значения реестра извлекаются и используются в шестнадцатеричном режиме. REG_DWORD registry values are extracted and used in hexadecimal mode.

Файловый режим поддерживает синтаксический анализ только текстовых файлов возврата каретки и перевода строки (CRLF). File mode supports the parsing of carriage return and line feed (CRLF) text files only.

При выполнении этой команды на существующей переменной удаляются все ссылки на переменные и используются расширенные значения. Running this command on an existing variable removes any variable references and uses expanded values.

Например, если переменная% PATH% имеет ссылку на% ЖАВАДИР%, а% PATH% обрабатывается с помощью Setx, то% жавадир% развернут и его значение присваивается непосредственно целевой переменной% PATH%. For instance, if the variable %PATH% has a reference to %JAVADIR%, and %PATH% is manipulated using setx, %JAVADIR% is expanded and its value is assigned directly to the target variable %PATH%. Это означает, что будущие обновления% ЖАВАДИР% не будут отражены в переменной% PATH%. This means that future updates to %JAVADIR% will not be reflected in the %PATH% variable.

Имейте в виду, что при назначении содержимого переменной с помощью Setxсуществует ограничение в 1024 символов. Be aware there’s a limit of 1024 characters when assigning contents to a variable using setx.

Это означает, что содержимое обрезается, если выйдет более 1024 символов, а обрезанный текст будет применен к целевой переменной. This means that the content is cropped if you go over 1024 characters, and that the cropped text is what’s applied to the target variable. Если этот обрезанный текст применяется к существующей переменной, это может привести к утрате данных, ранее удерживаемых целевой переменной. If this cropped text is applied to an existing variable, it can result in loss of data previously held by the target variable.

Примеры Examples

Чтобы задать для переменной среды машины в локальной среде значение Brand1, введите: To set the MACHINE environment variable in the local environment to the value Brand1, type:

Чтобы задать переменную среды компьютера в системной среде на значение Brand1 Computer, введите: To set the MACHINE environment variable in the system environment to the value Brand1 Computer, type:

Чтобы задать переменную среды MYPATH в локальной среде для использования пути поиска, определенного в переменной среды path , введите: To set the MYPATH environment variable in the local environment to use the search path defined in the PATH environment variable, type:

Чтобы задать переменную среды MYPATH в локальной среде для использования пути поиска, определенного в переменной среды path после замены

with %, type:

Чтобы задать переменную среды компьютера в локальной среде для Brand1 на удаленном компьютере с именем COMPUTER1, введите: To set the MACHINE environment variable in the local environment to Brand1 on a remote computer named computer1, type:

Чтобы задать переменную среды MYPATH в локальной среде для использования пути поиска, определенного в переменной среды path на удаленном компьютере с именем COMPUTER1, введите: To set the MYPATH environment variable in the local environment to use the search path defined in the PATH environment variable on a remote computer named computer1, type:

Чтобы задать переменную среды тзоне в локальной среде в качестве значения, находящихся в разделе реестра HKEY_LOCAL_MACHINE \систем\куррентконтролсет\контрол\тимезонеинформатион\стандарднаме , введите: To set the TZONE environment variable in the local environment to the value found in the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TimeZoneInformation\StandardName registry key, type:

Чтобы задать переменную среды тзоне в локальной среде удаленного компьютера с именем COMPUTER1 , в значение, найденное в разделе реестра HKEY_LOCAL_MACHINE \систем\куррентконтролсет\контрол\тимезонеинформатион\стандарднаме , введите: To set the TZONE environment variable in the local environment of a remote computer named computer1 to the value found in the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TimeZoneInformation\StandardName registry key, type:

Чтобы задать переменную среды сборки в системной среде в качестве значения, находящихся в разделе реестра HKEY_LOCAL_MACHINE \софтваре\микрософт\виндовснт\куррентверсион\куррентбуилднумбер , введите: To set the BUILD environment variable in the system environment to the value found in the HKEY_LOCAL_MACHINE\Software\Microsoft\WindowsNT\CurrentVersion\CurrentBuildNumber registry key, type:

Чтобы задать переменную среды сборки в системной среде удаленного компьютера с именем COMPUTER1, в качестве значения, находящихся в разделе реестра HKEY_LOCAL_MACHINE \софтваре\микрософт\виндовснт\куррентверсион\куррентбуилднумбер , введите: To set the BUILD environment variable in the system environment of a remote computer named Computer1 to the value found in the HKEY_LOCAL_MACHINE\Software\Microsoft\WindowsNT\CurrentVersion\CurrentBuildNumber registry key, type:

Источник

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

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

  • Services exe что это за процесс windows 7
  • Services exe грузит процессор windows xp
  • Servicedefaultregistryentries zip windows 7
  • Service pack for microsoft windows kb976932
  • Service pack 2 для windows vista x32 rus