- Команда SET — работа с переменными среды Windows
- File Types and File Associations
- Additional Resources
- File Types
- Public and Private File Types
- Registering a File Type
- Setting Optional Subkeys and File Type Extension Attributes
- Deleting Registry Information During Uninstallation
- File Types That Support Open Metadata
Команда SET — работа с переменными среды Windows
    Команда SET используется для просмотра и изменения переменных среды окружения в командной строке Windows. Переменные окружения — это переменные, принимаемые значения которых характеризуют среду, в которой выполняется текущая программа — пути системных файлов, сведения об аппаратных средствах, каталоги пользователя и т.п. Значения переменных среды формируются в процессе загрузки Windows, регистрации пользователя в системе, при выполнении отдельных процессов или с помощью команды SET . Для просмотра значения, принимаемого конкретной переменной можно воспользоваться командой :
SET переменная
SET PATH — отобразить значение переменной PATH
Для создания новой переменной, или изменения значения существующей, используется команда :
переменная — Имя переменной среды.
строка — Строка символов, присваиваемая указанной переменной.
SET MyName=Vasya — установить значение переменной MyName
SET path=C:\progs;%path% — изменить значение переменной PATH , добавив в начало строки C:\progs
Значение, принимаемое переменной , доступно для обработки в командных файлах, при использовании ее имени, заключенного в знаки процента — % . Например команда выдачи текста на дисплей ECHO в виде:
ECHO date — выведет на экран слово «date», а команда
ECHO %date% выведет на экран значение переменной date , т.е. текущую дату в формате операционной системы.
Команда SET без параметров используется для вывода текущих значений переменных среды.
ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\Usr\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
COMPUTERNAME=TEST7
ComSpec=C:\windows\system32\cmd.exe
FP_NO_HOST_CHECK=NO
HOMEDRIVE=C:
HOMEPATH=\Users\Usr
LOCALAPPDATA=C:\Users\Usr\AppData\Local
LOGONSERVER=\\TEST7
NUMBER_OF_PROCESSORS=2
OS=Windows_NT
Path=C:\windows\system32;C:\windows;
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS; .VBE;.JS;.JSE;.WSF;.WSH;.MSC
PROCESSOR_ARCHITECTURE=x86
PROCESSOR_IDENTIFIER=x86 Family 15 Model 3 Stepping 4, GenuineIntel
PROCESSOR_LEVEL=15
PROCESSOR_REVISION=0304
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
PROMPT=$P$G
PSModulePath=C:\windows\system32\Windows PowerShell\v1.0\Modules\
PUBLIC=C:\Users\Public
SystemDrive=C:
SystemRoot=C:\windows
TEMP=C:\Users\Usr\AppData \Local\Temp
TMP=C:\Users\Usr\AppData \Local\Temp
USERDOMAIN=test7
USERNAME=Usr
USERPROFILE=C:\Users\Usr
windir=C:\windows
Кроме переменных, отображаемых в списке, при вызове команды SET, существуют и другие, значения которых изменяется динамически:
%CD% — принимает значение текущего каталога.
%DATE% — принимает значение текущей даты.
%TIME% — принимает значение текущего времени.
%RANDOM% — значение случайного числа в диапазоне между 0 и 32767.
%ERRORLEVEL% — текущее значение ERRORLEVEL, специальной переменной, которая используется в качестве признака результата выполнения программы.
%CMDEXTVERSION% значение версии расширенной обработки команд CMD.EXE.
%CMDCMDLINE% — раскрывается в исходную командную строку, которая вызвала командный процессор .
Если при вызове команды SET указать только часть имени, то будет выведен список переменных, имена которых начинаются с указанной строки. Например:
SET U — выведет значения всех переменных, имена которых начинаются с ‘U’.
Команда SET поддерживает два дополнительных ключа:
SET /A выражение
SET /P variable=[promptString]
Ключ /A указывает, что строка справа от знака равенства является числовым выражением, значение которого вычисляется. Обработчик выражений очень прост и поддерживает следующие операции, перечисленные в порядке убывания приоритета:
() * / % + — > & ^ | = , | — группировка — арифметические операторы — арифметические операторы — двоичный сдвиг — двоичное И — двоичное исключающее ИЛИ — двоичное ИЛИ — присвоение — разделитель операторов |
При использовании любых логических или двоичных операторов необходимо заключить строку выражения в кавычки. Любые нечисловые строки в выражении рассматриваются как имена переменных среды, значения которых преобразуются в числовой вид перед использованием. Если переменная с указанным именем не определена в системе, вместо нее подставляется нулевое значение. Это позволяет выполнять арифметические операции со значениями переменных среды, причем не нужно вводить знаки % для получения значений. Если команда SET /A вызывается из командной строки, а не из пакетного файла, она выводит окончательное значение выражения. Слева от любого оператора присваивания должно стоять имя переменной среды. Числовые значения рассматриваются как десятичные, если перед ними не стоит префикс:
0x — для шестнадцатеричных чисел
0 — для восьмеричных чисел.
Пример использования префиксов:
SET /A REZ=0xA+012
ECHO %REZ%
В данном командном файле значение переменной REZ вычисляется сложением числа 10, представленного в шестнадцатеричном виде ( 0xA ) и числа 10 , представленного в восьмеричном ( 012 ).
Ключ /P позволяет установить значение переменной для входной строки, введенной пользователем. Показывает указанное приглашение promptString перед чтением введенной строки. Приглашение promptString может быть пустым. Данный ключ позволяет организовать диалог с пользователем в командном файле:
@ECHO OFF
SET /P NAME=Введите имя пользователя:
SET /P pass=Введите пароль:
ECHO Имя пользователя — %NAME% , Пароль — %PASS%
В командных файлах довольно часто требуется работать с частью значения, принимаемого переменной, для чего используются подстановочные значения:
переменная:строка1=строка2 — заменяет в принимаемом значении переменной строку1 на строку2
Следующий командный файл использует замену символа «точка» на символ «тире» в значении переменной, соответствующем текущей дате:
@ECHO OFF
set tm=%DATE%
ECHO Дата1 = %tm%
SET tm=%DATE:.=-%
ECHO Дата2 = %tm%
Для выделения части значения, принимаемого переменной, используется следующая конструкция:
x,y — где x — число пропускаемых символов от начала строки, а y — количество символов, используемых в качестве значения переменной.
Следующий пример использует отображение текущего времени без секунд и долей секунд (только первые 5 символов из стандартного значения переменной TIME):
@ECHO OFF
set tm=%TIME%
ECHO Время1 = %tm%
SET tm=%TIME:
0,5%
ECHO Время2 = %tm%
Если значение y ( длина ) не указана, то используется оставшееся до конца строки значение переменной. Если значение y отрицательно, то используется часть строки значения переменной от конца. Предыдущий пример можно изменить , указав, что в принимаемом значении времени отбрасываются 6 символов от конца:
@ECHO OFF
set tm=%TIME%
ECHO Время1 = %tm%
SET tm=%TIME:
Возможно использование число пропусков не задано, и используется отрицательное число, то принимаемое значение будет частью переменной от конца строки:
-10% — извлечет последние 10 символов переменной PATH
. Нулевое значение можно не указывать, сохраняя формат подстановки:
0,-2% эквивалентно %PATH:
При использовании переменных окружения в командных файлах существует определенное ограничение, связанное с тем фактом, что присваиваемое значение остается без изменения при его модификации внутри группы команд, задаваемой скобками, например в командах IF или FOR . Для обхода данного ограничения используется запуск командного процессора с параметром /V:ON и вместо знаков процента, для получения принимаемого переменной значения, используются восклицательные знаки. Кроме того, существует возможность использовать стандартный запуск командного процессора, но с локальным включением данного режима командой :
Разница в результатах использования значений переменных довольно наглядно демонстрируется следующим командным файлом:
Setlocal EnableDelayedExpansion
@ECHO OFF
set VAR=before
if «%VAR%» == «before» (
set VAR=after
if «!VAR!» == «after» @echo Со знаком процента=%VAR% , Со знаком вопроса=!VAR!
)
Команда set VAR=after выполняется внутри подпрограммы, ограниченной скобками и, если убрать команду Setlocal EnableDelayedExpansion или не использовать для получения значения переменной VAR восклицательные знаки, ее значение останется старым ( тем, что было установлено до входа в подпрограмму ). Аналогичная же проблема наблюдается и тогда, когда значение переменной изменяется внутри цикла команды FOR . Например, для получения списка файлов текущего каталога такой командный файл не будет работать:
set LIST=
for %%i in (*) do set LIST=%LIST% %%i
echo %LIST%
Значение переменной LIST внутри цикла изменено не будет. Для того, чтобы это произошло, командный файл нужно изменить следующим образом:
Setlocal EnableDelayedExpansion
set LIST=
for %%i in (*) do set LIST=!LIST! %%i
echo %LIST%
Теперь, значение переменной LIST внутри цикла FOR будет изменяться, последовательно принимая значения имен файлов, разделенных пробелом ( set LIST=!LIST! %%i )
File Types and File Associations
This section on file types and file associations is organized as follows:
Additional Resources
- Set Program Access and Computer Defaults (SPAD) is a Windows Control Panel which allows users with administrative privilege to set a machine default and hide or show an application. Media, Mail, Browser, Messenger and Java applications are examples of applications registered in SPAD. Set Your Default Programs (SYDP) is a Windows Control Panel, that works with limited privileges, and permits users to set a user default. Any application can register in SYDP. For information about SPAD and SYDP application registration, see Guidelines for File Associations and Default Programs, and Set Program Access and Computer Defaults (SPAD).
- For related conceptual background, see Overview of Verbs and File Associations.
- To create a Shell data store, see Implementing the Basic Folder Object Interfaces.
For related reference documentation, see the following topics:
- To execute a verb on a Shell item, see the InvokeVerb method.
- To retrieve a collection of verbs that can be executed on a Shell item, see the Verbs method.
- For performing an operation on a specified file, see either the ShellExecute or ShellExecuteEx functions.
- For a list of default perceived types, see the PERCEIVED enumeration.
- To retrieves a file’s perceived type based on its extension, see the AssocGetPerceivedType function.
File Types
This topic explains how to create new file types and how to associate your app with your file type and other well-defined file types. Files with a shared common file name extension (.doc, .html, and so on) are of the same type. For example, if you create a new text editor, then you can use the existing .txt file type. In other cases, you might need to create a new file type.
This topic is organized as follows:
Additional information can be found on the following topics:
Public and Private File Types
Public file types are also known as popular or contentious types because competing applications might want to be associated with these file types. Characteristics of public file types include:
- They are typically defined by standards bodies, and/or are promoted by their defining organizations as interchange formats.
- They are often exchanged between computers and users for diverse purposes.
- They need to be supported on many different platforms.
- Applications from multiple vendors are likely to handle them.
Some examples of file types that are considered public are the image file types .png, .gif, .jpg, and .bmp, and the audio types .wav, .mp3, and .au.
Unlike public file types, private or proprietary file types typically have a format that is implemented and understood by only one application or vendor. As a result, private file types are typically not prone to conflicts between applications. Some file types can start as private file types but later become public file types.
Windows does not differentiate between public and private file types. The distinction is relevant only in making decisions about your choice of file type registration.
Registering a File Type
To associate the file type with an existing application, locate the application ProgID in the registry. To associate the file type with a new application, define a ProgID for your application. For information about defining a new ProgID, see Programmatic Identifiers.
File name extension subkeys have the following general form: extension=ProgID. File name extension subkeys are stored in the HKEY_CLASSES_ROOT subtree.
It is important to include the leading period (.) when creating file type subkeys in the registry. For example, if you want a file type with the short extension .myp and the long extension .myp-file to be opened with an application called MyProgram, use the following syntax:
As demonstrated in the preceding example, if you also register a short file name extension (.myp), you should create a subkey for the long extension (.myp-file) as well. For more information, see File Type Handlers.
Setting Optional Subkeys and File Type Extension Attributes
File type extension entries in the registry have several optional subkeys and attributes.
The file type extension entries that are used by file associations are described in the following table. All values are of the REG_SZ type.
Registry entry | Action |
---|---|
Default | Set the default value of the extension subkey to the ProgID to which it is linked. |
Content Type | Set the Content Type value to the file type’s MIME content type. |
OpenWithList | Do not use. This subkey contains one or more application subkeys for applications that appear in the Open with dialog box entry for the file type and is intended only for .exe applications on operating systems prior to WindowsВ XP. Use OpenWithProgIds instead. |
OpenWithProgIds | This subkey contains a list of alternate ProgIDs for this file type. The programs for these ProgIDs appear in the Open with menu and are available as default Windows Store apps for the file type. Whenever an application takes over this file type by changing the default value, it should also add an entry to this list. |
PerceivedType | Set the PerceivedType value to the PerceivedType to which the file belongs, if any. This string is not used by Windows versions prior to WindowsВ Vista. For more information, see Perceived Types and Application Registration. |
The general form of a file name extension subkey is as follows. All entry types are of the REG_SZ type.
Important considerations about file types include:
The HKEY_CLASSES_ROOT subtree is a view formed by merging HKEY_CURRENT_USER\Software\Classes and HKEY_LOCAL_MACHINE\Software\Classes
In general, HKEY_CLASSES_ROOT is intended to be read from but not written to. For more information, see the HKEY_CLASSES_ROOT article.
To register a file type globally on a particular computer, create an entry for the file type in the HKEY_LOCAL_MACHINE\Software\Classes subkey.
To make a file type registration visible to the current user only, create an entry for the file type in the HKEY_CURRENT_USER\Software\Classes subkey.
An application can provide its own implementation of a verb, such as open or play, as shown in the following registry example.
Subkeys of the verb subkey include the command line and the drop target method: command and DropTarget.
When you create or change a file association, it is important to notify the system that you have made a change. Do so by calling SHChangeNotify and specifying the SHCNE_ASSOCCHANGED event. If you do not call SHChangeNotify, the change may not be recognized until after the system is rebooted.
To retrieve registry information regarding a file association, use the IQueryAssociations interface. For a scenario that illustrates this procedure, see File Association Sample Scenario.
Both the App Paths and Applications registry subkeys are used to register and control the behavior of the system on behalf of applications. For more detailed information about this functionality, see Application Registration.
Deleting Registry Information During Uninstallation
When uninstalling an application, the ProgIDs and most other registry information associated with that application should be deleted as part of the uninstallation. However, applications that have taken ownership of a file type (by setting the Default value of the file type’s HKEY_CLASSES_ROOT\.extension subkey to the ProgID of the application) should not attempt to remove that value when uninstalling. Leaving the data in place for the Default value avoids the difficulty of determining whether another application has taken ownership of the file type and overwritten the Default value after the original application was installed. Windows respects the Default value only if the ProgID found there is a registered ProgID. If the ProgID is unregistered, it is ignored.
Note that other file-type ownership information is stored in the HKEY_CURRENT_USERsubtree and also is used only when the application that it references is registered. Therefore, this data does not need to be removed when uninstalling an application.
As an example, the following shows the state of the registry before an application is uninstalled:
The following shows the state of those same registry entries after the application has been uninstalled.
File Types That Support Open Metadata
In WindowsВ 7 and later, the following file types support open metadata.