Команда set в командной строке windows

Внутри командных файлов можно работать с так называемыми переменными среды (или переменными окружения), каждая из которых хранится в оперативной памяти, имеет свое уникальное имя, а ее значением является строка. Стандартные переменные среды автоматически инициализируются в процессе загрузки операционной системы. Такими переменными являются, например, WINDIR, которая определяет расположение каталога Windows, TEMP, которая определяет путь к каталогу для хранения временных файлов Windows или PATH, в которой хранится системный путь (путь поиска), то есть список каталогов, в которых система должна искать выполняемые файлы или файлы совместного доступа (например, динамические библиотеки). Кроме того, в командных файлах с помощью команды SET можно объявлять собственные переменные среды.

Работа с переменными среды

Внутри командных файлов можно работать с так называемыми переменными среды (или переменными окружения), каждая из которых хранится в оперативной памяти, имеет свое уникальное имя, а ее значением является строка. Стандартные переменные среды автоматически инициализируются в процессе загрузки операционной системы. Такими переменными являются, например, WINDIR, которая определяет расположение каталога Windows, TEMP, которая определяет путь к каталогу для хранения временных файлов Windows или PATH, в которой хранится системный путь (путь поиска), то есть список каталогов, в которых система должна искать выполняемые файлы или файлы совместного доступа (например, динамические библиотеки). Кроме того, в командных файлах с помощью команды SET можно объявлять собственные переменные среды.

Получение значения переменной

Для получения значения определенной переменной среды нужно имя этой переменной заключить в символы %. Например:

@ECHO OFF
CLS
REM Создание переменной MyVar
SET MyVar=Привет
REM Изменение переменной
SET MyVar=%MyVar%!
ECHO Значение переменной MyVar: %MyVar% 
REM Удаление переменной MyVar
SET MyVar=
ECHO Значение переменной WinDir: %WinDir%

При запуске такого командного файла на экран выведется строка

Значение переменной MyVar: Привет!
Значение переменной WinDir: C:WINDOWS
Преобразования переменных как строк

С переменными среды в командных файлах можно производить некоторые манипуляции. Во-первых, над ними можно производить операцию конкатенации (склеивания). Для этого нужно в команде SET просто написать рядом значения соединяемых переменных. Например,

SET A=Раз
SET B=Два
SET C=%A%%B%

После выполнения в файле этих команд значением переменной C будет являться строка ‘РазДва’. Не следует для конкатенации использовать знак +, так как он будет воспринят просто в качестве символа. Например, после запуска файла следующего содержания

SET A=Раз
SET B=Два
SET C=A+B
ECHO Переменная C=%C%
SET D=%A%+%B%
ECHO Переменная D=%D%

на экран выведутся две строки:

Переменная C=A+B
Переменная D=Раз+Два

Во-вторых, из переменной среды можно выделять подстроки с помощью конструкции %имя_переменной:~n1,n2%, где число n1 определяет смещение (количество пропускаемых символов) от начала (если n1 положительно) или от конца (если n1 отрицательно) соответствующей переменной среды, а число n2 – количество выделяемых символов (если n2 положительно) или количество последних символов в переменной, которые не войдут в выделяемую подстроку (если n2 отрицательно). Если указан только один отрицательный параметр -n, то будут извлечены последние n символов. Например, если в переменной %DATE% хранится строка «21.09.2007» (символьное представление текущая дата при определенных региональных настройках), то после выполнения следующих команд

SET dd1=%DATE:~0,2%
SET dd2=%DATE:~0,-8%
SET mm=%DATE:~-7,2%
SET yyyy=%DATE:~-4%

новые переменные будут иметь такие значения: %dd1%=21, %dd2%=21, %mm%=09, %yyyy%=2007.

В-третьих, можно выполнять процедуру замены подстрок с помощью конструкции %имя_переменной:s1=s2% (в результате будет возвращена строка, в которой каждое вхождение подстроки s1 в соответствующей переменной среды заменено на s2 ). Например, после выполнения команд

SET a=123456
SET b=%a:23=99%

в переменной b будет храниться строка «199456». Если параметр s2 не указан, то подстрока s1 будет удалена из выводимой строки, т.е. после выполнения команды

SET a=123456
SET b=%a:23=%

в переменной b будет храниться строка «1456».

Операции с переменными как с числами

При включенной расширенной обработке команд (этот режим в Windows XP используется по умолчанию) имеется возможность рассматривать значения переменных среды как числа и производить с ними арифметические вычисления. Для этого используется команда SET с ключом /A. Приведем пример пакетного файла add.bat, складывающего два числа, заданных в качестве параметров командной строки, и выводящего полученную сумму на экран:

@ECHO OFF
REM В переменной M будет храниться сумма
SET /A M=%1+%2
ECHO Сумма %1 и %2 равна %M%
REM Удалим переменную M
SET M=
Локальные изменения переменных

Все изменения, производимые с помощью команды SET над переменными среды в командном файле, сохраняются и после завершения работы этого файла, но действуют только внутри текущего командного окна. Также имеется возможность локализовать изменения переменных среды внутри пакетного файла, то есть автоматически восстанавливать значения всех переменных в том виде, в каком они были до начала запуска этого файла. Для этого используются две команды: SETLOCAL и ENDLOCAL. Команда SETLOCAL определяет начало области локальных установок переменных среды. Другими словами, изменения среды, внесенные после выполнения SETLOCAL, будут являться локальными относительно текущего пакетного файла. Каждая команда SETLOCAL должна иметь соответствующую команду ENDLOCAL для восстановления прежних значений переменных среды. Изменения среды, внесенные после выполнения команды ENDLOCAL, уже не являются локальными относительно текущего
пакетного файла; их прежние значения не будут восстановлены по завершении выполнения этого файла.

Связывание времени выполнения для переменных

При работе с составными выражениями (группы команд, заключенных в круглые скобки) нужно учитывать, что переменные среды в командных файлах используются в режиме раннего связывания. С точки зрения логики выполнения командного файла это может привести к ошибкам. Например, рассмотрим командный файл 1.bat со следующим содержимым:

SET a=1
ECHO a=%a% 
SET a=2
ECHO a=%a%

и командный файл 2.bat:

SET a=1
ECHO a=%a% 
(SET a=2
ECHO a=%a% )

Казалось бы, результат выполнения этих двух файлов должен быть одинаковым: на экран выведутся две строки: «a=1» и «a=2». На самом же деле таким образом сработает только файл 1.bat, а файл 2.bat два раза выведет строку «a=1»!

Данную ошибку можно обойти, если для получения значения переменной вместо знаков процента (%) использовать восклицательный знак (!) и предварительно включить режим связывания времени выполнения командой SETLOCAL ENABLEDELAYEDEXPANSION. Таким образом, для корректной работы файл 2.bat должен иметь следующий вид:

SETLOCAL ENABLEDELAYEDEXPANSION 
SET a=1
ECHO a=%a% 
(SET a=2
ECHO a=!a! )

Приостановка выполнения командных файлов

Для того, чтобы вручную прервать выполнение запущенного bat-файла, нужно нажать клавиши <Ctrl>+<C> или <Ctrl>+<Break>. Однако часто бывает необходимо программно приостановить выполнение командного файла в определенной строке с выдачей запроса на нажатие любой клавиши. Это делается с помощью команды PAUSE. Перед запуском этой команды полезно с помощью команды ECHO информировать пользователя о действиях, которые он должен произвести. Например:

ECHO Вставьте дискету в дисковод A: и нажмите любую клавишу
PAUSE

Команду PAUSE обязательно нужно использовать при выполнении потенциально опасных действий (удаление файлов, форматирование дисков и т.п.). Например,

ECHO Сейчас будут удалены все файлы в C:Мои документы!
ECHO Для отмены нажмите Ctrl-C
PAUSE
DEL "C:Мои документы*.*"

Смотрите также «Полный список переменных окружения Windows».

Как вывести все переменные окружения в командной строке

Чтобы показать все переменные окружения и их значения в командной строке используйте команду:

SET

Чтобы вывод огранить одним экраном с возможностью пролистывания списка, используйте следующую конструкцию:

SET | more

Для сохранения вывода в файл:

SET > output.txt

Этот текстовый файл output.txt можно открыть в любом редакторе, например в Notepad.

Для показа значения переменной используйте знакомую команду set:

set ПЕРЕМЕННАЯ

Например:

set PATH

Команда set выводит значение всех переменных, которые начинаются на строку ПЕРЕМЕННАЯ. К примеру, предыдущая команда выведет значение переменных PATH и PATHEXT.

А следующая команда выведет значения всех переменных, чьё имя начинается на P:

set P

Как установить значение переменной

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

В после выполнения этой команды вам будет показано приглашение командной строки для ввода значения переменной:

SET /P ПЕРЕМЕННАЯ=

Например:

SET /P variable=

Второй вариант:

SET /P ПЕРЕМЕННАЯ=ЗАПРОС

Пример использования:

SET /P variable=Ведите значение:

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

%PATH:str1=str2%

расширит действие переменной среды PATH, заменяя каждое вхождение «str1» в расширенном результате на «str2». «str2» может быть пустой строкой для эффективного удаления вхождений «str1» из расширенного вывода. «str1» может начинаться со звёздочки, и в этом случае это будет соответствовать любому началу расширенного вывода до первого вхождения оставшейся части «str1».

Как удалить переменную

Чтобы удалить переменную, используйте следующую команду:

SET ПЕРЕМЕННАЯ=

В результате будет полностью удалена ПЕРЕМЕННАЯ. Обратите внимание, что используется знак равенства, но в отличие от предыдущей команды, не используется флаг /P. Поэтому значение не просто становится равным пустой строке, а происходит удаление переменной целиком.

Связанные статьи:

  • Как в командной строке Windows вывести все переменные среды (100%)
  • Переменные окружения Windows (65.8%)
  • Работа с переменными окружения в PowerShell (65.8%)
  • Основы запуска и использования утилит командной строки в Windows (65.8%)
  • Как узнать точную версию и номер сборки Windows (52.2%)
  • Windows 11 теперь доступна в виде бета-версии (RANDOM — 50%)

Переменные. Команда SET

Задание переменных

Вручную

Ввод с клавиатуры

set /p x="BBeduTe cTpoky: "

Типы переменных

Тип строка

Ограничение 8184 символа.
Тип число

Ограничение от -2147483647 до 2147483647.

Использование переменных

Вывод значения переменных

Существующие переменные

%RANDOM% — раскрывается в случайное десятичное число между 0 и 32767.(от 0 до (2^17)-1)

set /a random10=%random%/3277

Выводит случайное число от 0 до 9.
У меня это число по нелепой псевдослучайности цифру секунды
%CD% — раскрывается в строку текущей директории.
%DATE% — раскрывается в текущую дату, используя тот же формат команды DATE.
%TIME% — раскрывается в текущую дату, используя формат команды TIME.
%ERRORLEVEL% — раскрывается в текущее значение ERRORLEVEL.
Уровень ошибки, 0 — это нет ошибки, 1 — это есть ошибка, а другие это номера ошибки.

Чтобы получить полный список переменных и их значений введите команду SET

Операции со строковыми или численными переменными

Соединение 2-ух строковых переменных

set x=Gaz
set y=Prom
echo %x%%y%
(GazProm)

Вывод определенного(ых) символа(ов) из строки

Символы номеруются начиная с 0!

Вывод 1-ого символа

Вывод 3-х символов с конца строки

Вывод всей строки кроме 2-ух первых символов

Вывод всей строки кроме 2-ух последних символов

Вывод 3-х символов начиная с 3

Удаление подстроки из строки

set str=babywka
echo %str:ba=%
(bywka)

Замена подстроки из строки на другую подстроку

set str=babywka
echo %str:bab=xlop%
(xlopywka)

Удаление кавычек(«) из строки

set str2="qwerty"
echo %str2:"=%
(qwert)

В данном случае: если кавычки в начале и конце строки — можно юзать

echo %str2:~1,-1%
(qwert)

Существуют 2 способа использовать переменную в переменной, например:

вывод n-ого символа

Первый способ с call set

call set x=%%str:~%n%,1%%
echo %x%

Второй способ с for и setlocal enabledelayedexpansion

setlocal enabledelayedexpansion
for /l %%i in (%n%,1,%n%) do (set x=!str:~%%i,1!)
echo %x%

тут неважно что в for писать, главное

писать в do
С циклами мы разберемся в следующей статье.
Но, пока уточню: если код второго способа юзать в пакетном файле (BATнике), то вместо %i юзаем %%i.

Операции с числовыми переменными

Увеличивание на единицу

Увеличивание в 2 раза

аналогично

Возведение в квадрат

Возведение в куб

Деление
Деление в CMD является целочисленным!(то есть делится до целого числа)

set /a x=15
set /a y=4
set /a xy=%x%/%y%
(3)

Сложение

set /a x=5
set /a y=-6
set /a xy=%x%+%y%
(5+(-6)=5-6=-1)

Вычитание

set /a x=5
set /a y=-6
set /a xy=%x%-%y%
(5-(-6)=5+6=11)

Вычисление остатка от деления

(при записи в батник, процент «%» нужно удваивать «%%»)

Унарные операторы

Логическое отрицание (Logical NOT)

дает результат(%y%) 1 (True), если переменная(%x%) равна 0 (False), и 0 (False) (%y%) в любых других случаях

Например
set /a x=5
set /a y="!"%x%
(0)
set /a x=0
set /a y="!"%x%
(1)

Побитовая инверсия (Bitwise NOT):

дает результат -1-%x% (%y%)
Например

set /a x=5
set /a y="~"%x%
(-1-5=-(1+5)= -6)
set /a x=-3
set /a y="~"%x%
(-1-(-3)=-1+3=3-1= 2)

Унарный минус (устанавливает/сбрасывает знаковый бит)

дает результат 0-%x% (%y%)
Например

set /a x=5
set /a y="-"%x%
(-5)
set /a x=-3
set /a y="-"%x%
(3)

Двоичные операторы

set x=3
(в двоичной системе счисления - 0011)
set y=5
(в двоичной системе счисления - 0101)

Побитовое И (AND)

Побитовое И — это бинарная операция, действие которой эквивалентно применению логического И к каждой паре битов, которые стоят на одинаковых позициях в двоичных представлениях операндов.
Другими словами, если оба соответствующих бита операндов равны 1, результирующий двоичный разряд равен 1; если же хотя бы один бит из пары равен 0, результирующий двоичный разряд равен 0.

set /a xy=%x%"&"%y%
(1, в двоичной системе счисления - 0001)

Побитовое ИЛИ (OR)

Побитовое ИЛИ — это бинарная операция, действие которой эквивалентно применению логического ИЛИ к каждой паре битов, которые стоят на одинаковых позициях в двоичных представлениях операндов.
Другими словами, если оба соответствующих бита операндов равны 0, двоичный разряд результата равен 0; если же хотя бы один бит из пары равен 1, двоичный разряд результата равен 1.

set /a xy=%x%"|"%y%
(7, в двоичной системе счисления - 0111)

Побитовое исключающее ИЛИ (XOR)

Побитовое исключающее ИЛИ (или побитовое сложение по модулю два) — это бинарная операция, действие которой эквивалентно применению логического исключающего ИЛИ к каждой паре битов, которые стоят на

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

set /a xy=%x%"^"%y%
(6, в двоичной системе счисления - 0110)

К битовым операциям также относят битовые сдвиги. При сдвиге значения битов копируются в соседние по направлению сдвига.
Различают сдвиг влево (в направлении от младшего бита к старшему) и вправо (в направлении от старшего бита к младшему).
При логическом сдвиге значение последнего бита по направлению сдвига теряется (копируясь в бит переноса), а первый приобретает нулевое значение.

Двоичный арифметический сдвиг

Арифметический сдвиг аналогичен логическому, но значение слова считается знаковым числом, представленным в дополнительном коде.
Так, при правом сдвиге старший бит сохраняет свое значение. Левый арифметический сдвиг идентичен логическому.

Вправо

set /a xy=%x%">>"1
(1, в двоичной системе счисления - 0011->0001)
set /a xy2=%y%">>"1
(2, в двоичной системе счисления - 0101->0010)
set /a n=13
(в двоичной системе счисления - 1101)
set /a xn=%n%">>"2
(3, в двоичной системе счисления - 1101->0011)
set /a my=-%y%">>"1
(-3, в двоичной системе счисления - 1011(-5)->1101(-3))

Влево

set /a xy=%x%"<<"1
(6, в двоичной системе счисления - 0011->0110)
set /a xy2=%y%"<<"1
(10, в двоичной системе счисления - 0101->1010)
set /a xy3=%y%"<<"4
(80, в двоичной системе счисления - 0101->1010000)
set /a my=-%y%"<<"1
(-10, в двоичной системе счисления - 1011(-5)->10110(-10))

Максимальный размер отдельной переменной среды составляет 8192 байта.(у меня выходило только 8184, наверное это вместе с названием…)
Максимальный общий размер всех переменных среды, включая имена переменных и знак равенства, составляет 65 536 Кбайт.

И я забыл, про 8-ричную и 16-ричную систему счисления в CMD

Системы счисления

Числовые значения рассматриваются как десятичные, если перед ними не стоит префикс 0x для шестнадцатеричных чисел, и 0 для восьмеричных чисел. Например, числа 0x12, и 022 обозначают десятичное число 18.

Обратите внимание на запись восьмеричных числе: 08 и 09 не являются допустимыми числами, так как в восьмеричной системе исчисления цифры 8 и 9 не используются.

Восьмеричная система счисления

set /a x=022
(Это 22 в восьмеричной системе счисления, и 18 в десятичной)

Можно производить все операции, также как и с десятеричными числами.
Но после задания значения переменной, значение хранится в десятичной системе счисления.
Например, сложение

set /a xy=022+07
(Это 22+7=31 в восьмеричной системе счисления, и 31 в десятичной)

Шестнадцатеричная система счисления

set /a x=0x3A
(Это 3A в восьмеричной системе счисления, и 58 в десятичной)

Вычитание

set /a xy=0x3A-0x66
(Это 3A-66=-54 в восьмеричной системе счисления, и -44 в десятичной)

Сохранение в переменной вывода программы
К сожаление, передача вывода программ на вход команды set не работает:

echo 1|set /p AA=""
set AA

Поэтому можно воспользоваться временным сохранением в файл:

echo 1> 0.tmp
set /p AA="" <0.tmp
del 0.tmp
echo %AA%

Примеры использования
Узнать динамически генерируемое имя архива WinRar:

rar a -z%Comment% -p%p% "-ag yyyy-mm-dd[n]" %OutPath%%arhivename%.%ext% @%FileList% >rar.log.tmp
for /f "tokens=2*" %%I in ('find /i "Creating archive" ^<rar.log.tmp') do @echo %%J >rarfilename.tmp
set /p rarfilename="" <rarfilename.tmp
del rarfilename.tmp

Узнать имя последнего изменённого файла в папке:

dir /b /a-d /o-d *.* >%temp%.tmp
set /p lastfile="" <%temp%.tmp
del %temp%.tmp
echo "%lastfile%"

Комментарий от Dragokas :
По сути эта команда считывает в переменную первую строку файла:

Комментарий от m00slim25:
Эти операции, как и все остальные, поддерживают кавычный синтаксис:

set /a "y=!%x%"
set /a "y=~%x%"
set /a "y=-%x%"

Оператор == используется только для строчного сравнения. Кавычки необходимы если в переменной/операнде имеются пробелы.
Для арифметического сравнения необходимо использовать арифметические операторы:
EQU : Равно (=)
NEQ : Не равно (!=)
LSS : Меньше (<)
LEQ : Меньше или равно (<=)
GTR : Больше (>)
GEQ : Больше или равно (>=)
Использовать операторы, указанные в скобках, не представляется возможным, потому что, например, операторы < и > являются указателями перенаправления ввода-вывода.

Updated: 03/13/2021 by

set command

The set command lets users change one variable or string to another.

Availability

Set is an internal command that is available in the following Microsoft operating systems.

  • All Versions of MS-DOS
  • Windows 95
  • Windows 98
  • Windows ME
  • Windows NT
  • Windows 2000
  • Windows XP
  • Windows 7
  • Windows 8
  • Windows 10
  • Windows 11

Set syntax

  • Windows 2000, XP, and later syntax.
  • Windows 2000 and Windows XP Recovery Console syntax.
  • MS-DOS, Windows 95, Windows 98, Windows ME syntax.

Windows 2000, XP, and later syntax

Displays, sets, or removes cmd.exe environment variables.

SET [variable=[string]]
variable Specifies the environment variable name.
string Specifies several characters to assign to the variable.

Type SET without parameters to display the current environment variables.

If Command Extensions are enabled SET changes as follows:

SET command invoked with a variable name, no equal sign or value displays the value of all variables whose prefix matches the name given to the SET command. For example:

SET P

would display all variables that begin with the letter ‘P.’

SET command sets the ERRORLEVEL to 1 if the variable name is not found in the current environment.

SET command doesn’t allow an equal sign to be part of the name of a variable.

Two new switches are added to the SET command:

SET /A expression
SET /P variable=[promptString]

The /A switch specifies that the string to the right of the equal sign is a numerical expression that is evaluated. The expression evaluator is pretty simple and supports the following operations, in decreasing order of precedence:

() — grouping
* / % Arithmetic operators.
+ — Arithmetic operators.
<< >> Logical shift.
& Bitwise and.
^ Bitwise exclusive or.
| Bitwise or.
= *= /= %= += -=
&= ^= |= <<= >>=
Assignment.
, Expression separator.

If you use any of the logical or modulus operators, you need to enclose the expression string in quotes. Any non-numeric strings in the expression are treated as environment variable names whose values are converted to numbers before using them. If an environment variable name is specified but is not defined in the current environment, then a value of zero is used. Doing this lets you do arithmetic with environment variable values without having to type all those % signs to get their values. If SET /A is executed from the command line outside of a command script, then it displays the final value of the expression. The assignment operator requires an environment variable name to the left of the assignment operator. Numeric values are decimal numbers unless prefixed by 0x for hexadecimal numbers, and 0 for octal numbers. So 0x12 is the same as 18 is the same as 022. Note: the octal notation can be confusing: 08 and 09 are not valid numbers because 8 and 9 are not valid octal digits.

The /P switch lets you set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

Environment variable substitution is enhanced as follows:

%PATH:str1=str2%

would expand the PATH environment variable, substituting each occurrence of str1 in the expanded result with str2. str2 can be the empty string to effectively delete all occurrences of str1 from the expanded output. str1 can begin with an asterisk, which matches everything from the beginning of the expanded output to the first occurrence of the remaining portion of str1.

May also specify substrings for an expansion.

%PATH:~10,5%

would expand the PATH environment variable, and then use only the 5 characters that begin at the 11th (offset 10) character of the expanded result. If the length is not specified, then it defaults to the remainder of the variable value. If either number (offset or length) is negative, then the number used is the length of the environment variable value added to the offset or length specified.

%PATH:~-10%

would extract the last 10 characters of the PATH variable.

%PATH:~0,-2%

would extract all but the last 2 characters of the PATH variable.

Finally, support for delayed environment variable expansion was added. This support is always disabled by default, but may be enabled/disabled via the /V command line switch to CMD.EXE. See CMD /?

Delayed environment variable expansion is useful to get around the limitations of current expansion that happens when reading a line of text, not when it is executed. The following example demonstrates the problem with immediate variable expansion:

set VAR=before
if "%VAR%" == "before" (
set VAR=after;
if "%VAR%" == "after" @echo If you see this, it worked
)

would never display the message, because %VAR% is expanded when the lie is read into memory. Changes that occur to the variable after that (such as VAR=after in our compound if statement) is not expanded.

Similarly, the following example will not work as expected:

set LIST=
for %i in (*) do set LIST=%LIST% %i
echo %LIST%

in that it will NOT build up a list of files in the current directory, but instead set the LIST variable to the last file found. Again, this is because the %LIST% expandeds once the FOR statement is read, and the LIST variable is empty. So the actual FOR loop we are executing is:

for %i in (*) do set LIST= %i

which keeps setting LIST to the last file found.

Delayed environment variable expansion allows a different character (the exclamation mark) to expand environment variables at execution time. If delayed variable expansion is enabled, the above examples could be written as follows to work as intended:

set VAR=before
if "%VAR%" == "before" (
set VAR=after
if "!VAR!" == "after" @echo If you see this, it worked
)
set LIST=
for %i in (*) do set LIST=!LIST! %i
echo %LIST%

If Command Extensions are enabled, then several dynamic environment variables can be expanded, which don’t show up.

The list of variables displayed by SET. These variable values are computed dynamically each time the value of the variable is expanded. If the user explicitly defines a variable with one of these names, then that definition overrides the dynamic one described below:

%CD% — expands to the current directory string.

%DATE% — expands to the current date using the same format as DATE command.

%TIME% — expands to the current time using the same format as TIME command.

%RANDOM% — expands to a random decimal number between 0 and 32767.

%ERRORLEVEL% — expands to the current ERRORLEVEL value

%CMDEXTVERSION% — expands to the current Command Processor Extensions version number.

%CMDCMDLINE% — expands to the original command line that invoked the command processor.

%HIGHESTNUMANODENUMBER% — expands to the highest NUMA node number on this machine.

Windows 2000 and Windows XP Recovery Console syntax

set [enviroment_variable]=[True/False]
[enviroment_variable] allowwildcards
allowallpaths
allowremovablemedia
nocopyprompt
[True/False] Setting the enviroment_variable to true enables the enviroment_variable. By default, these are set to False.

MS-DOS, Windows 95, Windows 98, Windows ME syntax

Displays, sets, or removes Windows environment variables.

SET [variable=[string]]
variable Specifies the environment variable name.
string Specifies several characters to assign to the variable.

Type SET without parameters to display the current environment variables.

Set examples

set path=c:windowscommand

Set the path to c:windowscommand.

set

Display all the set environment variables currently defined.

How to use the set command as a substitute for the choice command in Windows 2000 and Windows XP

In the example below, a user would be prompted to enter an option of 1,2, or 3 to print hello, bye, or test.

@ECHO off
cls
:start
ECHO.
ECHO 1. Print Hello
ECHO 2. Print Bye
ECHO 3. Print Test
set choice=
set /p choice=Type the number to print text.
if not '%choice%'=='' set choice=%choice:~0,1%
if '%choice%'=='1' goto hello
if '%choice%'=='2' goto bye
if '%choice%'=='3' goto test
ECHO "%choice%" is not valid, try again
ECHO.
goto start
:hello
ECHO HELLO
goto end
:bye
ECHO BYE
goto end
:test
ECHO TEST
goto end
:end

Secret commands

If you wanted to hide all your directories from users, you could use:

SET DIRCMD=0

The above command prevents anyone from seeing the directories; however, they can still be accessed. To allow the directories to be visible again, type the command below.

SET DIRCMD=

Rob van der Woude's Scripting Pages

Windows NT 4..Windows 7 Syntax

Displays, sets, or removes cmd.exe environment variables.

SET [variable=[string]]

variable Specifies the environment-variable name.
string Specifies a series of characters to assign to the variable.

Type SET without parameters to display the current environment variables.

If Command Extensions are enabled SET changes as follows:

SET command invoked with just a variable name, no equal sign or value will display the value of all variables whose prefix matches the name given to the SET command. For example:

SET P

would display all variables that begin with the letter ‘P’

SET command will set the ERRORLEVEL to 1 if the variable name is not found in the current environment.

SET command will not allow an equal sign (=) to be part of the name of a variable (with the exception of some dynamic environment variables).
However, SET command will allow an equal sign in the value of an environment variable in any position other than the first character.

Integer Math

The /A switch was introduced in Windows NT 4:

SET /A expression

The /A switch specifies that the string to the right of the equal sign is a numerical expression that is evaluated.
The expression evaluator is pretty simple and supports the following operations, in decreasing order of precedence:

() grouping
* / % arithmetic operators
+ — arithmetic operators
<< >> logical shift
& bitwise and
ˆ bitwise exclusive or
| bitwise or
= *= /= %= += -=
&= ˆ= |= <<= >>=
assignment
, expression separator

If you use any of the logical or modulus operators, you will need to enclose the expression string in quotes.
Any non-numeric strings in the expression are treated as environment variable names whose values are converted to numbers before using them.
If an environment variable name is specified but is not defined in the current environment, then a value of zero is used.
This allows you to do arithmetic with environment variable values without having to type all those % signs to get their values.
If SET /A is executed from the command line outside of a command script, then it displays the final value of the expression.
The assignment operator requires an environment variable name to the left of the assignment operator.
Numeric values are decimal numbers, unless prefixed by 0x for hexadecimal numbers, 0b for binary numbers and 0 for octals numbers.
So 0x12 is the same as 0b10010 is the same as 022 is the same as 18.
Please note that the octal notation can be confusing: 08 and 09 are not valid numbers because 8 and 9 are not valid octal digits.

Note: A note on NT 4’s SET /A switch from Walter Zackery in a message on alt.msdos.batch.nt:

«The SET /A command has a long list of problems.
I wouldn’t use it for much more than simple arithmetic, although even then it truncates all answers to integers.»

On the other hand, limited though it may seem, the SET command’s math function can even be used for a complex task like calculating the date of Easter Day for any year.
But always keep in mind that it is limited to 16- or 32-bit integers, depending on the Windows version.

More on integer math, and its limitations, can be found on my Batch math and PHP based batch files pages.

Prompt For Input

The /P switch was introduced in Windows 2000:

SET /P variable=[promptString]

The /P switch allows you to set the value of a variable to a line of input entered by the user.
Displays the specified promptString before reading the line of input.
The promptString can be empty.

Note: If nothing is entered, and only the Enter key is pressed, variable will remain unchanged instead of being cleared.
My own SecondChoice.bat uses this feature to allow pressing Enter to get a preset default value.

String Substitution

Environment variable substitution has been enhanced as follows:

%PATH:str1=str2%

would expand the PATH environment variable, substituting each occurrence of «str1» in the expanded result with «str2».
«str2» can be the empty string to effectively delete all occurrences of «str1» from the expanded output.
«str1» can begin with an asterisk, in which case it will match everything from the beginning of the expanded output to the first occurrence of the remaining portion of str1.

Note: I’m not sure about other Windows versions, but in Windows XP and Windows 7 string substitution is case-insensitive, e.g. SET Var=%Var:A=A% will convert all occurrences of the letter a in variable Var into upper case As (tip by Brad Thone & Brian Williams).

Substrings

May also specify substrings for an expansion.

%PATH:~10,5%

would expand the PATH environment variable, and then use only the 5 characters that begin at the 11th (offset 10) character of the expanded result.
If the length is not specified, then it defaults to the remainder of the variable value.
As of Windows 2000, if either number (offset or length) is negative, then the number used is the length of the environment variable value added to the offset or length specified.

%PATH:~-10%

would extract the last 10 characters of the PATH variable.

%PATH:~0,-2%

would extract all but the last 2 characters of the PATH variable.

Delayed Variable Expansion

Finally, support for delayed environment variable expansion has been introduced in Windows 2000.
This support is always disabled by default, but may be enabled/disabled via the /V command line switch to CMD.EXE.
See CMD /?

Delayed Variable Expansion

Delayed environment variable expansion is useful for getting around the limitations of the current expansion which happens when a line of text is read, not when it is executed.
The following example demonstrates the problem with immediate variable expansion:

SET VAR=before
IF "%VAR%" == "before" (
	SET VAR=after;
	IF "%VAR%" == "after" @ECHO If you see this, it worked
)

would never display the message, since the %VAR% in BOTH IF statements is substituted when the first IF statement is read, since it logically includes the body of the IF, which is a compound statement.
So the IF inside the compound statement is really comparing «before» with «after» which will never be equal.
Similarly, the following example will not work as expected:

SET LIST=
FOR %A IN (*) DO SET LIST=%LIST% %A
ECHO %LIST%

in that it will NOT build up a list of files in the current directory, but instead will just set the LIST variable to the last file found.
Again, this is because the %LIST% is expanded just once when the FOR statement is read, and at that time the LIST variable is empty.
So the actual FOR loop we are executing is:

FOR %A IN (*) DO SET LIST= %A

which just keeps setting LIST to the last file found.

Delayed environment variable expansion allows you to use a different character (the exclamation mark) to expand environment variables at execution time.
If delayed variable expansion is enabled, the above examples could be written as follows to work as intended:

SET VAR=before
IF "%VAR%" == "before" (
	SET VAR=after
	IF "!VAR!" == "after" @ECHO If you see this, it worked
)

SET LIST=
FOR %A IN (*) DO SET LIST=!LIST! %A
ECHO %LIST%

Dynamic Environment Variables

As of Windows 2000, if Command Extensions are enabled, then there are several dynamic environment variables that can be expanded but which don’t show up in the list of variables displayed by SET.
These variable values are computed dynamically each time the value of the variable is expanded.
If the user explicitly defines a variable with one of these names, then that definition will override the dynamic one described below:

%=C:% expands to the current directory string on the C: drive
%=D:% expands to the current directory string on the D: drive if drive D: has been accessed in the current CMD session
%=ExitCode% expands to the hexadecimal value of the last return code set by EXIT /B
%=ExitCodeAscii% expands to the ASCII value of the last return code set by EXIT /B if greater than 32 (decimal)
%__APPDIR__% expands to the requesting executable’s (CMD.EXE for batch files) parent folder, always terminated with a trailing backslash
%__CD__% expands to the current directory string, always terminated with a trailing backslash
%CD% expands to the current directory string (no trailing backslash, unless the current directory is a root directory)
%CMDCMDLINE% expands to the original command line that invoked the Command Processor
%CMDEXTVERSION% expands to the current Command Processor Extensions version number
%DATE% expands to current date using same format as DATE command
%ERRORLEVEL% expands to the current ERRORLEVEL value
%HIGHESTNUMANODENUMBER% expands to the highest NUMA node number on this machine
%RANDOM% expands to a random decimal number between 0 and 32767
%TIME% expands to current time using same format as TIME command
Notes: 1 The first 6 dynamic variables listed here (the ones on a grey background) are not listed in SET‘s on-screen help text.
  2 The first 4 dynamic variables listed (the ones starting with the equal sign) were discovered by «SmartGenius».
The current values are revealed using the command SET ""
I do not know if these variables are available in Windows 2000.
«SmartGenius» supplied the following demo script:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%A IN (83 109 97 114 116 71 101 110 105 117 115) DO (
    CMD /C EXIT /B %%A
    SET /P "Var=!=ExitCodeAscii!" < NUL
)
ECHO.
ENDLOCAL

Try it, it is harmless…

  3 The following sample code, by Thomas Freundt, lists all %=D:% like variables:

FOR /F "tokens=* delims==" %%A IN ('SET "" ˆ| FINDSTR.EXE /B "="') DO @ECHO.%%A

Or a simplified version for the command line, if you don’t mind a more cluttered output:

SET "" | FINDSTR.EXE /B "="

  4 If %=D:% is not available (not verified for Windows 2000 or NT 4) it can be emulated by the following code:

PUSHD D:
SET CDD=%CD%
POPD

  5 The dynamic variable %__APPDIR__% was discovered by Carlos Montiers.
I do not know if this variables is available in Windows 2000.
  6 The dynamic variable %__CD__% was discovered by Menno Vogels.
I do not know if this variables is available in Windows 2000.

ErrorLevels

Andrew Pixley reported that in Windows XP, «unsetting» a variable (SET variable=) will set the ErrorLevel to 1, whereas setting it again (SET variable=value) will not reset the ErrorLevel to 0.
In Windows 7, SET only sets the ErrorLevel to 1 with a SET variable command (no equal sign) if variable is not set.


page last modified: 2021-01-27

Понравилась статья? Поделить с друзьями:
  • Коды активации office 2016 на windows 10 бесплатно
  • Коды ошибок синего экрана windows 10 полный список
  • Кодовые страницы таблиц преобразования windows xp
  • Кодовая таблица windows 1251 содержит определенные группы символов выберите какие
  • Кодовая таблица windows 1251 двоичный код