Поделиться через


setx

Создает или изменяет переменные среды в пользовательской или системной среде, не требуя программирования или скриптов. The Setx command also retrieves the values of registry keys and writes them to text files.

Note

Эта команда предоставляет только командную строку или программный способ непосредственного и постоянного задания системных значений среды. System environment variables are manually configurable through Control Panel or through a registry editor. The set command, which is internal to the command interpreter (Cmd.exe), sets user environment variables for the current console window only.

Syntax

setx [/s <computer> [/u [<domain>\]<user name> [/p [<password>]]]] <variable> <value> [/m]
setx [/s <computer> [/u [<domain>\]<user name> [/p [<password>]]]] <variable>] /k <path> [/m]
setx [/s <computer> [/u [<domain>\]<user name> [/p [<password>]]]] /f <filename> {[<variable>] {/a <X>,<Y> | /r <X>,<Y> <String>} [/m] | /x} [/d <delimiters>]

Parameters

Parameter Description
<computer> Указывает имя или IP-адрес удаленного компьютера. Не используйте обратные очки. Значение по умолчанию — имя локального компьютера.
[<domain>\]<user name> Запускает скрипт с учетными данными указанной учетной записи пользователя. Значение по умолчанию — это разрешения системы.
/p [<password>] Specifies the password of the user account that is specified in the /u parameter.
<variable> Указывает имя переменной среды, которую требуется задать.
<value> Указывает значение, для которого необходимо задать переменную среды.
<path> Указывает, что переменная устанавливается на основе сведений из раздела реестра. The path uses the following syntax: \\<HIVE>\<KEY>\...\<Value>. Например, можно указать следующий путь: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TimeZoneInformation\StandardName
<filename> Указывает файл, который требуется использовать.
/a <X>,<Y> Задает абсолютные координаты и смещение в качестве параметров поиска.
<X>,<Y> <String> Specifies relative coordinates and offset from String as search parameters.
/m Указывает, чтобы задать переменную в системной среде. Параметр по умолчанию — локальная среда.
/x Displays file coordinates, ignoring the /a, /r, and /d command-line options.
<delimiters> Specifies delimiters such as , or \ to be used in addition to the four built-in delimiters — SPACE, TAB, ENTER, and LINEFEED. Допустимые разделители включают любой символ ASCII. Максимальное число разделителей равно 15, включая встроенные разделители.
/? Отображение справки в командной строке.

Remarks

  • Эта команда аналогична служебной программе UNIX SETENV.

  • Эту команду можно использовать для задания значений переменных пользовательской и системной среды из одного из трех источников (режимов): режима командной строки, режима реестра или режима файлов.

  • Эта команда записывает переменные в главную среду в реестре. Variables set with setx variables are available in future command windows only, not in the current command window.

  • HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE are the only supported hives. REG_DWORD, REG_EXPAND_SZ, REG_SZ, and REG_MULTI_SZ are the valid RegKey data types.

  • If you gain access to REG_MULTI_SZ values in the registry, only the first item is extracted and used.

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

  • REG_DWORD значения реестра извлекаются и используются в шестнадцатеричном режиме.

  • Режим файла поддерживает только синтаксический анализ возвращаемых каретки и текстовых файлов канала строк (CRLF).

  • При выполнении этой команды в существующей переменной удаляются все ссылки на переменные и используются развернутые значения.

    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%. This means that future updates to %JAVADIR% will not be reflected in the %PATH% variable.

  • Be aware there's a limit of 1024 characters when assigning contents to a variable using setx.

    Это означает, что содержимое обрезается при переходе на 1024 символов и что обрезанный текст применяется к целевой переменной. Если этот обрезанный текст применяется к существующей переменной, это может привести к потере данных, ранее удерживаемых целевой переменной.

Examples

To set the MACHINE environment variable in the local environment to the value Brand1, type:

setx MACHINE Brand1

To set the MACHINE environment variable in the system environment to the value Brand1 Computer, type:

setx MACHINE Brand1 Computer /m

To set the MYPATH environment variable in the local environment to use the search path defined in the PATH environment variable, type:

setx MYPATH %PATH%

To set the MYPATH environment variable in the local environment to use the search path defined in the PATH environment variable after replacing ~ with %, type:

setx MYPATH ~PATH~

To set the MACHINE environment variable in the local environment to Brand1 on a remote computer named computer1, type:

setx /s computer1 /u maindom\hiropln /p p@ssW23 MACHINE Brand1

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:

setx /s computer1 /u maindom\hiropln /p p@ssW23 MYPATH %PATH%

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:

setx TZONE /k HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TimeZoneInformation\StandardName

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:

setx /s computer1 /u maindom\hiropln /p p@ssW23 TZONE /k HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TimeZoneInformation\StandardName

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:

setx BUILD /k HKEY_LOCAL_MACHINE\Software\Microsoft\WindowsNT\CurrentVersion\CurrentBuildNumber /m

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:

setx /s computer1 /u maindom\hiropln /p p@ssW23  BUILD /k HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\CurrentBuildNumber /m

To display the contents of a file named Ipconfig.out, along with the contents' corresponding coordinates, type:

setx /f ipconfig.out /x

To set the IPADDR environment variable in the local environment to the value found at the coordinate 5,11 in the Ipconfig.out file, type:

setx IPADDR /f ipconfig.out /a 5,11

To set the OCTET1 environment variable in the local environment to the value found at the coordinate 5,3 in the Ipconfig.out file with delimiters #$*., type:

setx OCTET1 /f ipconfig.out /a 5,3 /d #$*.

To set the IPGATEWAY environment variable in the local environment to the value found at the coordinate 0,7 with respect to the coordinate of Gateway in the Ipconfig.out file, type:

setx IPGATEWAY /f ipconfig.out /r 0,7 Gateway

To display the contents of the Ipconfig.out file, along with the contents' corresponding coordinates, on a computer named computer1, type:

setx /s computer1 /u maindom\hiropln /p p@ssW23 /f ipconfig.out /x