• BAT file basics. Using environment variables on the command line

    (command) files, allow you to do without specifying absolute paths to directories. For example, if we do not know the system drive letter in advance, we can always use the variable %systemdrive%, which returns the drive letter on which the OS is installed. Also, variables are used to optimize code - a repeatedly repeated parameter (for example, a registry key) can be assigned a short variable and used. This article discusses in detail various techniques for working with variables, as well as ways to change and create new variables. Now let's talk about everything in order.

    Classification of environment variables
    Windows Help distinguishes between two types of environment variables: system and local. System variables return the same values ​​for all users. For example, %systemdrive%- the letter of the system drive, and it is the same for all users. But the values ​​returned by local variables vary depending on the logged in user. For example, %userprofile% can return C:\Documents and Settings\CurrentUser, where CurrentUser is the name of the user account.

    The command will help you find out which environment variables in the operating system are available to you and what values ​​are currently assigned to them SET, launched from the command line without parameters ( Start – Run – cmd – set). In this article, we are interested in variables that indicate the path to various folders (directories). A little more about some of them below:

    Variable|Type|Description
    %SYSTEMDRIVE%|System|Returns the name of the drive containing the root directory of the Windows XP/2003 operating system (that is, the system root directory).
    %SYSTEMROOT%, %WINDIR%|System|Returns the location of the root directory of the Windows /2003 operating system
    %PATH%|System|Specifies the search path for executable files.
    %PROGRAMFILES%|System|Indicates the path to the program installation directory (Program Files)
    %COMMONPROGRAMFILES%|System|Indicates the path to the common program directory (Program Files\Common Files).
    %TEMP% and %TMP%|System and User|Returns the default temporary folders used by applications that are accessible to logged-in users. Some applications require the TEMP variable, others require the TMP variable.
    %USERPROFILE%|Local|Returns the profile location for the current user.
    %ALLUSERSPROFILE%|Local|Returns the location of the "All Users" profile.
    %CD%|Local|Returns the path to the current folder.
    %APPDATA%|Local|Returns the default location of application data.

    Using Variables in Batch Files
    Let's start with a simple example:

    CMD/BATCH:

    DEL /F /Q "%AllUsersProfile%\Main Menu\Windows Activation.lnk" DEL /F /Q "%AllUsersProfile%\Main Menu\WindowsUpdate.lnk" DEL /F /Q "%systemroot%\system32\*.scr "

    In this example, I remove the above shortcuts that appear in the Start menu using the variable %AllUsersProfile%, as well as all files with the SCR extension from the Windows\system32 directory, using the variable %SystemRoot%. Instead of DEL /F /Q, as you understand, there can be anything: from the copy command COPY to the command to launch the installation of the application we need with all the command line parameters, if required.

    In all commands I specifically used “quotes” - this is not accidental. The entire path, including variables, must be enclosed in quotes if you are using paths that contain spaces. Even if the variable itself does not contain quotes, after it is parsed by the system, spaces may appear in the path (for example, %ProgramFiles% in C:\Program Files). In any case, it is better to use quotes - this is good practice when designing command files.

    How to set your variables

    The example above used already existing environment variables. And you probably noticed the percentage symbols surrounding the variable names. These characters are needed to allow variable value substitution on the command line or in a batch file. The percentage symbols indicate that Cmd.exe should access the values ​​of the variables rather than do a character-by-character comparison. Below you will see how it works. You can set your variables in a batch file with the SET command.

    SET command
    You can set your variables in the batch file using the same SET command.

    To add a variable, enter at the command line:

    Code:

    Set variable_name=value

    To display a variable, enter at the command line:

    Code:

    Set variable_name

    To remove a variable, enter at the command line:

    Code:

    Set variable_name=

    For example,

    Code:

    SET mydir=D:\Files\Work

    sets a variable mydir, which will return the path to the specified folder. You can read more about the team from set /?.

    Important Note: Variables set by the set command are valid only for the duration of the command session (see below) in which they were set.

    These variables can be created, for example, for any paths; you just need to set or find an algorithm for assigning a variable in each particular situation, using ready-made examples or creating your own based on them. Typically, such variables are created in the current session by batch files using some statements.

    Example of assigning variables in a file RunOnceEx.cmd importing settings into the registry

    CMD/BATCH:

    @echo off SET KEY=HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnceEx SET i=100 REG ADD %KEY% /V TITLE /D "Installing Applications" /f REG ADD %KEY%\%i% /VE /D "WinRar 3.51" /f REG ADD %KEY%\%i% /V 1 /D "%systemdrive%\install\Software\WinRar.exe /s" /f REG ADD %KEY%\%i% /V 2 / D "REGEDIT /S %systemdrive%\install\Software\rar_set.reg /s" /f SET /A i+=1

    In this script, the SET command sets two variables - %i% And %KEY%. Please note that they are specified without percent symbols, but to access them, %% is already needed. Variable %KEY% serves to simplify and optimize the code. It remains unchanged throughout the current command session, eliminating the need to include a registry key in the code each time. Every time it appears in the code %KEY%, it will be replaced by HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnceEx. But %i% serves for sequential numbering of registry sections. With an initial value of 100, the variable is incremented by one using the SET /A i+=1 command after each block of commands, resulting in the sequence 100, 101, 102, etc. So the line

    Code:

    REG ADD %KEY%\%i% /V 1 /D "%systemdrive%\install\Software\WinRar.exe /s" /f

    actually it will work like this

    Code:

    REG ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnceEx\100 /V 1 /D "C:\install\Software\WinRar.exe /s" /f

    Note that the file snippet also uses a system variable %systemdrive%, which corresponds to the system drive letter.

    An example of assigning variables in a command file that installs an application from a CD:

    Code:

    For %%i in (C D E F G H I J K L M N O P Q R S T U V W X Y Z) do if exist %%i:\WIN51 set CDROM=%%i: start /wait “%CDROM%\INSTALL\DVDTools\NBRom\Nero.exe”

    In this example, all listed drives are searched for a specific file (WIN51). If it is detected on one of the disks, the latter is assigned a variable %CDROM%, and then the software is installed using the path specified by the created variable.

    Changing environment variables and adding your own variables

    As mentioned above, the effect of variables set with the set command is limited to the current command session. If you want to get a system or user variable from a temporary variable, you need to register it in the registry. This can also be done in various ways.

    setenv utility
    The utility works from the command line (website, download). The utility is very easy to use (setenv /?).


    User settings|setenv -u variable_name value
    System settings|setenv -m variable_name value
    Settings Default User|setenv -d variable_name value
    Current user session settings|setenv -v variable_name value

    Let's say, if you need to get the %temp% variable at the installation stage, you can do this from cmdlines.txt , for example:

    Code:

    :: Creating and Setting Temp folder... md %systemdrive%\Temp setenv -u Temp %systemdrive%\Temp setenv -u Tmp %systemdrive%\Temp

    The utility is convenient because after setting a variable, it can be used immediately. Well, almost immediately - in the next team session. To use it in the current session, you can use the old familiar set command:

    Code:

    :: Creating #EgOrus# var set EgOrus=D:\EgOrus setenv -u EgOrus %EgOrus%

    Importing settings into the registry
    If you go by making changes to the registry after the first login, then the variables will begin to “work” only after a reboot or end of the user session. Of course, during the auto-installation process you can import the desired parameters to the T-12 (see the Registry Tweaks article) and bypass this problem. If you do not intend to use the assigned variable in the current user session, then importing into the registry may also suit you. I will not describe the process of importing REG files again, but will consider the REG ADD command using a specific example.

    Let's say you are interested in having a variable in the system %CDROM% permanently and install it during the installation of applications from the CD. Following the code above, after defining a variable, you need to assign it to the system variable.

    CMD/BATCH:

    For %%i in (C D E F G H I J K L M N O P Q R S T U V W X Y Z) do if exist %%i:\WIN51 set CDROM=%%i: REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v cdrom /d %CDROM% / f

    Once a WIN51 file is found, the drive on which it was found is assigned a local variable %CDROM%, which is immediately assigned as a constant system variable by importing it into the registry. This method was proposed in one of the topics at the Oszone Sanja Alone conference. At the same time you found out. where the system variable settings are stored in the registry. User variable settings are stored in HKCU\Environment. The paths returned by the %PROGRAMFILES% and %COMMONPROGRAMFILES% variables can be viewed in the ProgramFilesDir and CommonFilesDir parameters in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion, but should not be changed there. Program installation directories (other than %SystemDrive%\Program Files) must be configured through an answer file.

    Resume
    The Windows command shell (cmd.exe) is a very powerful tool for working with the system. Batch files can automate a fair amount of tasks, which is why they are often used to automatically install Windows. Skillful use of variables in batch files allows you to solve a wide range of issues. Working with the command shell becomes more efficient and at the same time the code of batch files is simplified. You can find other examples of using variables on the pages of the website or forum. All examples used in this article were taken from the scripts of OsZone.ru forum participants, for which many thanks to them.

    Terminology
    Command shell
    is a separate software product that provides direct communication between the user and the operating system. The command line text user interface provides an environment in which to run text-based applications and utilities.

    cmd.exe- a command interpreter that the Windows OS command shell uses to translate the entered command into a format understandable to the system.

    Team session can be initiated either by launch cmd.exe, and by running a batch file. In other words, the current command shell is created. Accordingly, exiting this shell (for example, finishing a batch file) ends the command session.

    User session(user session) begins when the user logs in (log on) and ends when the user logs off (log off).

    Inside batch files, you can work with so-called environment variables (or environment variables), each of which is stored in RAM, has its own unique name, and its value is a string. Standard environment variables are automatically initialized when the operating system boots. Such variables are, for example, WINDIR, which determines the location of the Windows directory, TEMP, which determines the path to the directory for storing temporary Windows files, or PATH, which stores the system path (search path), that is, the list of directories in which the system should look for executables. files or shared files (for example, dynamic libraries). You can also declare your own environment variables in batch files using the SET command.

    Getting the value of a variable

    To get the value of a specific environment variable, you need to enclose the name of that variable in % characters. For example:

    @ECHO OFF CLS REM Create variable MyVar SET MyVar=Hello REM Change variable SET MyVar=%MyVar%! ECHO MyVar variable value: %MyVar% REM Deleting MyVar variable SET MyVar= ECHO WinDir variable value: %WinDir%

    When you run such a batch file, the line will be displayed on the screen

    MyVar variable value: Hello! WinDir variable value: C:\WINDOWS

    Converting Variables as Strings

    There are some manipulations you can do with environment variables in batch files. Firstly, the operation of concatenation (gluing) can be performed on them. To do this, you just need to write the values ​​of the connected variables next to each other in the SET command. For example,

    SET A=One SET B=Two SET C=%A%%B%

    After executing these commands in the file, the value of the C variable will be the string "Double". You should not use the + sign for concatenation, as it will simply be interpreted as a symbol. For example, after running the file with the following content

    SET A=One SET B=Two SET C=A+B ECHO Variable C=%C% SET D=%A%+%B% ECHO Variable D=%D%

    Two lines will be displayed on the screen:

    Variable C=A+B Variable D=One+Two

    Secondly, you can extract substrings from an environment variable using the construct %variable_name:~n1,n2%, where the number n1 determines the offset (the number of characters to skip) from the beginning (if n1 is positive) or from the end (if n1 is negative) of the corresponding environment variable, and the number n2 is the number of characters to be allocated (if n2 is positive) or the number of last characters in the variable that will not be included in the selected substring (if n2 is negative). If only one negative -n option is specified, the last n characters will be extracted. For example, if the variable %DATE% stores the string "09/21/2007" (the symbolic representation of the current date in certain regional settings), then after running the following commands

    SET dd1=%DATE:~0.2% SET dd2=%DATE:~0.-8% SET mm=%DATE:~-7.2% SET yyyy=%DATE:~-4%

    the new variables will have the following values: %dd1%=21, %dd2%=21, %mm%=09, %yyyy%=2007.

    Thirdly, you can perform the substring replacement procedure using the construction %variable_name:s1=s2%(this will return a string with every occurrence of the substring s1 in the corresponding environment variable replaced by s2 ). For example, after executing the commands

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

    variable b will store the string "199456" . If the s2 parameter is not specified, then the substring s1 will be removed from the output string, i.e. after executing the command

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

    variable b will store the string "1456" .

    Operations with variables as with numbers

    When enhanced command processing is enabled (the default mode in Windows XP), it is possible to treat environment variable values ​​as numbers and perform arithmetic calculations on them. To do this, use the SET command with the /A switch. Here is an example of a batch file add.bat that adds two numbers given as command line parameters and displays the resulting sum on the screen:

    @ECHO OFF REM The variable M will store the sum SET /A M=%1+%2 ECHO The sum of %1 and %2 is equal to %M% REM Delete the variable M SET M=

    Local Variable Changes

    Any changes you make to environment variables in a command file using the SET command persist after the file exits, but are effective only within the current command window. It is also possible to localize changes to environment variables inside a batch file, that is, to automatically restore the values ​​of all variables as they were before the file was launched. Two commands are used for this: SETLOCAL and ENDLOCAL. The SETLOCAL command specifies the beginning of the local environment variable setting area. In other words, environment changes made after running SETLOCAL will be local to the current batch file. Each SETLOCAL command must have a corresponding ENDLOCAL command to restore the environment variables to their previous values. Environment changes made after the ENDLOCAL command are executed are no longer local to the current batch file; their previous values ​​will not be restored upon completion of execution of this file.


    0.00 (1 )

    General approach.

    Command files are text files with the extension bat or cmd, whose lines represent commands or names of executable files. When you run a batch file, control is taken over by the operating system's command processor (often called the command interpreter), which sequentially reads and interprets the lines in the batch file. For Windows9X this is done command.com, for WinNT/2K/XP - cmd.exe. Batch file lines can contain commands from the command processor itself (FOR, GOTO, IF, etc.) or names of executable modules (net.exe, regedit.exe, win.com, etc.). In WinNT/2K/XP operating systems, you can get brief help on the composition of commands using the command line:

    or by specific command:

    HELP Command name

    To display help text not on the screen, but in a file, you can use output redirection . When using the command line, the default input device is the keyboard and the output device is the display, however these devices can be remapped using redirection characters

    < - input redirection

    > - output redirection (or > > - redirection to an existing file, when the output data is appended to the end of the file.)

    To output the command data streamHELPin the help.txt file the command line will be as follows:

    HELP > help.txt

    To display help for the GOTO command in the goto.txt file:

    HELP GOTO > goto.txt

    Using environment variables.

    In batch files you can, and often should, use environment variables - variables whose values ​​characterize the environment in which the command or batch file is executed. The values ​​of environment variables are generated when the OS boots and the user registers in the system, and can also be set using the commandSET, the format of which is:

    SET [variable=[string]]

    variable Environment variable name.

    line A character string assigned to the specified variable.

    For example, command line

    SET mynane=Vasya

    will add a variable myname that takes the value Vasya.

    You can get the value of a variable in programs and batch files by using its name surrounded by percent signs ( %) . For example the command

    will display the word time, and the command

    will display the value of the time variable, which takes the value of the current time.

    And the command line

    SET PATH=C:myprog;%path%

    will add the C:myprog directory to the search path for executable programs, described by the value of the PATH variable

    Executing the SET command without parameters causes the current values ​​of the variables to be displayed on the screen, in the form:

    NUMBER_OF_PROCESSORS=1 - number of processors

    OS=Windows_NT - OS type

    Path=E:WINDOWSsystem32;E:WINDOWS;E:Program FilesFar - search path for executable files.

    PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH - extensions for executable files.

    PROCESSOR_ARCHITECTURE=x86 - processor architecture.

    PROCESSOR_IDENTIFIER=x86 Family 6 Model 8 Stepping 1, AuthenticAMD - processor identifier.

    PROCESSOR_LEVEL=6 - processor level (model number).

    PROCESSOR_REVISION=0801 - processor version.

    ProgramFiles=E:Program Files - path to the "Program Files" folder

    PROMPT=$P$G - command line prompt format $P - path for the current directory $G - ">" sign.

    SystemDrive=E: - system drive letter.

    SystemRoot=E:WINDOWS - Windows OS directory.

    The values ​​of some variables are not returned by the SET command. These are variables whose values ​​change dynamically:

    %CD% - Takes the value of the current directory string.

    %DATE% - Takes the value of the current date.

    %TIME% - Accepts the current time value.

    %RANDOM% - Accepts the value of a random decimal number in the range 1 -32767.

    %ERRORLEVEL% - Accepts the current value of the task's exit code ERRORLEVEL

    %CMDEXTVERSION% - Takes the value of the CMD.EXE command processor version for extended command processing.

    %CMDCMDLINE% - Takes the value of the line that called the shell.

    To view the value of a variable, you can use the command line:

    ECHO %variable%

    Input parameters for the batch file.

    It is possible to pass command line parameters to a command file and use their values ​​in statements in the command file itself.

    BAT file< параметр1 > , < параметр2 >, ... < параметрN >

    In the batch file itself, the first parameter will be available as a variable %1 , second - %2 etc. The name of the batch file itself is available as a variable %0 . For example, let's create a batch file whose task will be to display the values ​​of the entered parameters on the screen. Typically the command used to display text is

    ECHO< текст >

    However, if the text is replaced with %1, then the first parameter will be returned, with %2 - the second, etc.

    Create a parm.bat file with the following content:

    echo First parameter=%1

    echo Second parameter=%2

    echo Third parameter = %3

    and run it with the following command:

    parm.bat FIRST second “two words”

    After executing it, you will understand how it works and that parameters with spaces must be enclosed in double quotes. To prevent lines processed by the command processor from being displayed on the screen, you can use the commandECHO OFF, placing it on the first line of the batch file. To make a line in a batch file ignored by the shell, place it at the beginning of the lineR.E.M.< пробел > . This way you can place comments, which are often useful in large batch files:

    rem ECHO OFF turns off the mode of displaying the contents of command file lines on the screen

    REM will only display the result of their execution.

    echo First parameter=%1

    echo Second parameter=%2

    echo Third parameter = %3

    Try replacing ECHO OFF with @ECHO OFF - the result speaks for itself. The line that turns off the output mode is no longer displayed on the screen.

    Transitions and labels.

    In batch files, you can use conditional jump commands that change the logic of their operation depending on the fulfillment of certain conditions. To illustrate how to use conditional jumps, let's create a batch file whose purpose will be to assign a predetermined drive letter to removable media, which will be flash drives. The conditions are as follows - there are 2 flash drives, one of which should be visible in Explorer as drive X: and the second as drive Y:, regardless of which USB port they are connected to. We will assume that real disks can be connected as F: or G: We will identify disks by the presence of a file with a certain name (it is better to make such a file hidden in the root directory and name it something unusual):

    Flashd1.let - on the first disk

    Flashd2.let - on the second

    Those. The purpose of the batch file is to check for the presence of removable disks F: And G: files Flashd1.let or Flashd2.let and, depending on which one is present, assign a drive letter X: or Y:

    To search for a file on disk, use the commandIF EXIST:

    IF EXIST filename command

    The easiest way to use it as a command isSUBST, which matches the drive name and directory.

    SUBST X: C: - creates a virtual disk X:, the contents of which will be the root directory of drive C:

    Create a batch file setXY.bat with the following lines:

    After executing such a file, you will have drives X: and Y: But if you execute such a file again, the SUBST command will display an error message - after all, drives X: and Y: already exist.

    It is advisable to bypass execution of SUBST if virtual disks X: and Y: are already created (or delete them using SUBST with the -d parameter before mounting). Modify the batch file usingGOTO- transferring control to a line of a batch file by label.

    GOTO label

    The label must be on a separate line and begin with a colon. Let's make changes to our batch file so that we don't get error messages:

    REM if X does not exist - then go to the SETX label

    IF NOT EXIST X: GOTO SETX

    REM if X exists: - let's move on to checking the presence of Y:

    IF EXIST G:flashd1.let SUBST X: G:

    IF EXIST F:flashd1.let SUBST X: F:

    REM if Y: exists - complete the batch file.

    IF EXIST Y: GOTO EXIT

    IF EXIST G:flashd2.let SUBST Y: G:

    IF EXIST F:flashd2.let SUBST Y: F:

    REM exit from batch file

    The SUBST error message has disappeared. Signs of errors when executing commands can be tracked in the command file itself by analyzing the variableERRORLEVEL, the value of which is formed during the execution of most programs. ERRORLEVEL is 0 if the program completed without errors and 1 if an error occurred. There may be other values ​​if they are provided in the executing program.

    You can also use a batch file as a command on a line in a batch file. Moreover, to transfer and return back to the point of execution of the calling batch file, the command is usedCALL. Let's create a command file test.bat with the following content:

    ECHO Call 1.bat

    ECHO Return.

    And a 1.bat file containing the commandPAUSE,suspending the execution of a batch file until any key is pressed.

    When executing test.bat, a message will be displayed on the screen

    Call 1.bat

    and control will be given to 1.bat with the pause command. After pressing a key on the keyboard, control will be given to the command line “ECHO Return.” and it will be displayed on the screen

    If you remove CALL from test.bat, then the return from file 1.bat will not be performed. By the way, by transferring control to a batch file, you can organize it to loop. Try adding the following line to the end of the test.bat file:

    You can break out of the batch file loop by pressing the CTRL-Break combination. It is possible to use the CALL command to call a procedure within a batch file. In this case, the argument is not the name of the external file, but the label:
    ....
    call:proc1
    ....
    :proc1
    ....
    exit
    ....

    Creating files.

    There is no special command in Windows to create a file, but you can easily do without it in several ways:

    Copying from console to file

    COPY CON myfile.txt

    When this command is executed, the data from the keyboard (CON device) will be written to the file myfile.txt. Pressing F6 or CTRL-Z will complete the output.

    Output redirection

    ECHO 1 > myfile.txt

    Running this command will create a file myfile.txt containing the character “1”

    Combination of input and output redirection:

    COPY CON > myfile.txt< xyz

    When executing this command, as in the first case, copying from the console to a file is used, but instead of input from the keyboard, input from the non-existent device xyz is used. The system will display a message stating that such a device does not exist, but the empty file myfile.txt will be successfully created.
    A very simple option is to copy from a fictitious device with the name nul to file.
    copy null myfile.txt

    If you often need to create empty files, you can prepare your own batch file (for example, newfile.bat or, even better, nf.bat), and pass the name of the file to be created as a parameter when running.

    File Contents:

    Place this batch file in your system directory (C:windowssystem32 or whatever is in your PATH search path).

    Command line:

    newfile.bat myfile.txt

    Or

    nf.bat myfile.txt

    Or
    nf myfile.txt

    Here's your team nf to create an empty file on the command line.

    Assigning the same drive letter to a removable drive.

    The goal is to ensure that a removable USB drive (flash drive) is always accessible under the same letter, regardless of what computer it is used on and how it is connected. To solve it, we will use the SUBST command already mentioned above. Let's select the desired letter for the removable disk, for example - X. The name of the disk from which the batch file was launched is available as the variable %~d0. Create a batch file with the following content:
    @echo off
    subst X: %~d0
    which means creating a virtual disk X:, which is mapped to the physical disk from which the command file was launched.
    Additional insight into the substitution values ​​for the %0 variable can be obtained from the following batch file:

    @echo off
    ECHO FILE PROCESSING - %0
    ECHO Date/time the batch file was created/modified - %~t0
    ECHO Batch file path - "%~f0"
    ECHO Command file disk - %~d0
    ECHO Batch file directory - "%~p0"
    ECHO Batch file name - %~n0
    ECHO Batch file extension - %~x0
    ECHO Short name and extension - %~s0
    ECHO Batch file attributes - %~a0
    ECHO Batch file size - %~z0

    Creating generations of archives based on dates and times.

    Let's solve the following problem - we need to create an archive of files located in the C:Program FilesFAR directory. The name of the archive file must consist of the current time (hours.minutes.seconds - HH.MM.SS.rar), and it must be placed in a new directory, the name of which must consist of the current date (day.month.year - DD.MM. YYYY). For archiving we will use the RAR archiver. Launch format for creating an archive:

    RAR a -r< путь и имя архива > < Путь и имя архивируемых данных >

    a- archive creation command.
    -r- a key that determines the archiving of subdirectories (since there are subdirectories in the source folder).

    Thus, to solve the problem, you need to correctly create names and paths for RAR. For this we will use the following factors:

  • In batch files you can access the current date and current time - the variables %DATE% and %TIME%
  • In batch files, you can create temporary variables using the SET command.
  • The value of temporary variables can be formed based on %DATE% and %TIME% by omitting and (or) replacing their parts using the same SET command.

    The date obtained from the %DATE% variable with standard regional settings looks like this:
    Mon 01/21/2005- Day of the week (2 characters) - Space - date (10 characters)
    For example, let's create a directory with the MD command< имя каталога >.
    We create a temporary variable VDATE in memory and assign it the value of the environment variable DATE, without the first 3 characters - 01/20/2005:

    Set VDATE=%date:~3%

    Create a directory on drive C:, whose name = current date from the VDATE variable:

    MD C:\%VDATE%
    After executing this command, a directory named 01/20/2005 will be created on drive C:

    Time obtained from the %TIME% variable:
    14:30:59.93 - Hours, minutes, seconds, hundredths of a second.
    Hundredths are perhaps unnecessary in the archive file name. Create a temporary variable VTIME and assign it the current time without the last 3 characters
    set VTIME=%time:~0,-3%
    Now VTIME = 14:30:59, but the ":" sign cannot be used in the file name, so let's replace it with a dot.
    set VTIME=%VTIME::=.%
    The VTIME variable will take the value 14.30.59 For the file name it will do.

    Let's launch the archiver:

    Now you can create a batch file with the contents:

    Set VDATE=%date:~3%
    md c:\%VDATE%
    set VTIME=%time:~0,-3%
    set VTIME=%VTIME::=.%
    rar a -r C:\%VDATE%\%VTIME%.rar "C:Program filesfar*.*"

    Such a batch file can be executed through autoload, or as part of a script, when a user logs into the domain, or using a scheduler at a given time, and you will always have time-ordered archives of critical data.

    Creating archives using user profile variables.

    This batch file creates archives of the contents of the "My Documents" folder of Win2K/XP users, placing them in directories
    C:ARHIVMy documentsUsernameDateTime

    The variables USERPROFILE, USERNAME, WINDIR are used, so this batch file will not work in WIN9X. (Although, if you wish, you can insert commands into autoexec.bat to set the values ​​of these variables and use it in a single-user version with virtually no changes). The contents of the batch file are commented and should not cause much difficulty if you understand the previous example:

    @echo off
    rem Sets the FROM variable - where to get the data for archiving
    set FROM=%USERPROFILE%My Documents
    rem Sets the variable TO - where to place the archives
    set TO=C:arhivMy documents\%USERNAME%
    rem Let's create a maintenance directory
    md "%TO%"
    rem Let's form the name of the subdirectory from the current date
    rem current date with default settings for Win2K - Mon 04/25/2005
    rem current date with default settings for WinXP - 04/25/2005
    rem From the current date we will form the name of the subdirectory - 04/25
    rem By default Windir for WinXP is C:WINDOWS, and for Win2K - C:WINNT
    IF /I %Windir% == C:WINNT GOTO Win2K
    set vdate=%DATE:~0.-5%
    GOTO SetFileName
    :Win2K
    set vdate=%DATE:~3.-5%
    rem Let's create an archive file name from the current time - 12:00:00.99
    rem we will discard hundredths of a second and replace the symbol: with the symbol. Result - 12.00.00
    :SetFileName
    set vtime=%TIME:~0,-3%
    set vtime=%vtime::=.%
    rem Create a subdirectory for the archive file
    md "%TO%\%VDATE%"
    rem Command for archiving. The -r switch is needed for archiving with subfolders
    rem option for the ARJ archiver: arj a -r "%TO%\%VDATE%\%VTIME%.arj" "%FROM%*.*"
    rem When using the RAR archiver:
    rar a -r "%TO%\%VDATE%\%VTIME%.rar" "%FROM%*.*"

    Execute commands according to schedule.

    In WIN2K/XP there is a command line utilityAT,allows you to execute a command or batch file at a specified time on a local or remote computer. To use the AT command, the Task Scheduler service must be running (usually started by default during system installation).

    AT [\computername] [ [code] | /DELETE ]

    AT [\computername] time

    [ /EVERY:day[,...] | /NEXT:day[,...]] "command"

    \computername The name of the remote computer. If this parameter is omitted,

    local computer is used.

    code The sequence number of the scheduled task. Indicated if you need to cancel an already scheduled task using the key /delete.

    /delete Cancel a scheduled task. If the task code is omitted,

    cancels all tasks scheduled for the specified

    computer.

    /yes Cancel confirmation request when canceling all

    planned tasks.

    time Time to start the command.

    /interactive Allowing task interaction with the user,

    working on the computer when the task starts. Tasks launched without this key are invisible to the computer user.

    /every:day[,...] The task is launched on the specified days of the week or

    month. If date is omitted, current day is used

    /next:day[,...] The task will run on the next specified day of the week

    (for example next Thursday). If the date is omitted,

    The current day of the month is used.

    "team" Command or batch file name.

    Examples of use:

    An analogue of an “alarm clock”, - pop-up windows with text reminding the current or specified user about the need to perform some action. To send a message to the user we use the utilityNET.EXE

    AT 13:50 net.exe send * Time for coffee

    AT 17:50 net.exe send User Time to go home

    AT \SERVER 13:45 net.exe send You need to restart the server

    View the list of scheduled tasks:

    Deleting already scheduled tasks:

    AT 3 /DELETE- deleting task number 3

    AT /DELETE /YES- deleting all tasks

    “Control Panel” - “Scheduled Tasks” allow you to view, change and delete those created by the team AT tasks.

    Stopping and starting system services.

    To stop and start Win2K/XP services from the command line, use the NET.EXE command

    NET.EXE STOP< имя службы >

    NET.EXE START< имя службы >

    It is possible to use both a short and full name ("Dnscache" is a short name, "DNS client" is the full name of the service). Service names containing spaces are enclosed in double quotes. Example of restarting the “DNS Client” service

    net stop "DNS client"

    net start "DNS client"

    The same, using a short name:

    net stop Dnscache

    net start Dnscache

    The full name of the service can be copied from “Services” -< Имя службы >- “Properties” - “Display name”

    To manage services, it is much more convenient to use the PsService.exe utility from the PsTools utilities. The utility does not require installation and works on any Windows OS. In addition to starting and stopping a service, it allows you to search for a specific service on computers on the local network, poll the status and configuration of the service, change the startup type, pause the service, continue, restart.

    To work with system services in Windows XP, you can use the utility sc.exe, which allows you not only to stop/start a service, but also to poll its status, startup and operating parameters, change the configuration, and also work not only with system services, but also with drivers. If you have rights, you can manage services not only on the local machine, but also on a remote machine. Examples:
    sc.exe stop DNSCache- stop the DNSCache service on the local computer.
    sc\192.168.0.1 query DNSCache- poll the status of the DNSCache service on a computer with IP address 192.168.0.1
    sc\COMP start DNSCache start the DNSCache service on the COMP computer
    You can get help on working with the utility by entering:
    sc/?

    Displaying the value of the variable ERRORLEVEL.

    This simple batch file will display the value of the ERRORLEVEL variable on a specific command line. It first checks for the presence of at least one input parameter, and if none is given, an error message is issued and exit occurs. If at least one parameter is specified, then the input parameters are taken as the command line and executed, and the value ERRORLEVEL is returned using the ECHO command. Contents of the file (I called it echoEL.bat):

    @echo off
    if "%1" NEQ "" GOTO PARMOK
    ECHO You need to set the command line to define ERRORLEVEL
    exit
    :PARMOK
    %1 %2 %3 %4 %5 %6 %7 %8
    ECHO %1 %2 %3 %4 %5 %6 %7 %8 ERRORLEVEL=%ERRORLEVEL%

    Launch examples:
    echoEL.bat NET SHARE
    - the NET SHARE command will be executed (give a list of shared network resources) and the code ERRORLEVEL will be issued
    echoEL.bat NET SHARE X"="C:
    - the command NET SHARE X:=C: will be executed (create a shared network resource with the name X, and the path to the root directory of drive C:) Please note that the = symbol is enclosed in double quotes.
    The options listed above set the correct command line. But try to set the wrong parameter to NET.EXE or a non-existent command and you will see what value ERRORLEVEL will take. AND PLEASE NOTE that the command line actually EXECUTES and, for example, the option “echoEL.bat format A:” will start formatting the floppy disk in drive A:.

    Dialogue with the user

    To dialogue with the user, you can use the command:
    SET /P< имя переменной >=< текст >
    when executed, a text message is displayed on the screen< текст >and the response text is expected. Example - let's request a password and assign its value to the "pset" variable:

    Set /p pset="Enter password - "
    echo Password is - %pset%

    The disadvantage of this method is that it is impossible to continue executing a batch file if there is no user response, so very often third-party programs are used instead of set. One of them is CHOICE.COM Download (1.7kb).
    CHOICE gives the user a text message and waits for the user to select one of the given response options (keypresses on the keyboard). Based on the selection results, the ERRORLEVEL variable is formed, the value of which is equal to the ordinal number of the selection. By default there are two options - Y or N. If the answer is Y - then ERRORLEVEL=1, if N - then ERRORLEVEL=2. You can use more than 2 selection options and it is possible to set a default selection when the user has not pressed a single key for a certain time. Command line format:

    CHOICE choices] c,nn]
    /C[:]choices - defines valid choices. If not specified - YN
    /N - do not display selection options.
    /S - lowercase and uppercase letters are different.
    /T[:]c,nn - Default selection is "c" after "nn" seconds
    text - Text string output as a request

    Let's create a batch file demonstrating the use of CHOICE. It will respond to pressing the keys "1", "2", 3" and "0". When you press "0", it completes, and when you press the rest, a message is sent to the user. If nothing is pressed within 10 seconds, it completes.

    @ECHO OFF
    :CHOICE
    CHOICE /C:1230 /T:0.10 Your option
    IF %ERRORLEVEL% EQU 4 GOTO EXIT
    echo Your choice=%ERRORLEVEL%
    GOTO CHOICE
    :EXIT

    Now, using CHOICE you can create batch files, the logic of which can be defined by the user.

    Delays in batch files

    Once upon a time, back in DOS, the convenient SLEEP command was used to organize waiting in a batch file, but then for some reason it migrated from the standard Windows installation kit to the additional Resource Kit. You can simply copy it from there to the system32 directory and use it in your batch files.

    : SLEEP N - where N is the number of seconds to delay.

    If the Resource Kit is not at hand, you can use the previously discussed CHOISE command without text output and with automatic generation of a response in nn seconds (1-99):

    Choice.com /T:y,10 /N - delay for 10 seconds

    A more universal method is based on pinging the loopback interface with the required number of packets. Ping for the loopback interface (host name - localhost or IP address 127.0.0.1) is performed without actual data transmission, i.e. almost instantly, and the interval between pings is 1 second. By specifying the number of pings using the "-n" switch, you can get a delay of n seconds:

    Ping 127.0.0.1 -n 30 > nul - will give a delay of 30 seconds

    Search for computers running the application

    To implement this script, use the utilities from the package PSTools(brief description). Let's create a batch file that searches the local network for computers running a program, the name of which (the initial part of the name) is specified as a parameter at startup, for example, game . If detected, a message will be sent to the computer ADMINCOMP and the detected application will be forced to terminate. To search, we will use the Pslist.exe utility and analyze its return code. A value of the ERRORLEVEL variable equal to zero means that the utility has detected a process on the remote computer that satisfies the search conditions. We will set the name of the process to search as a parameter when running the batch file. Let's give our batch file a name psl.bat. Running with the parameter will look like this:
    psl.bat game
    First, we need to check whether the parameter is specified on the command line at startup, and if it is not specified, we will issue a message to the user and complete execution. If the parameter is specified, let's go to the "PARMOK" label:
    @echo off
    if "%1" NEQ "" GOTO PARMOK
    ECHO You need to specify the process name to search
    exit
    :PARMOK
    Now we need to ensure the consistent generation of computer IP addresses for the PSlist command line. The easiest way to do this is by assigning a temporary environment variable (valid only for the duration of the command file execution) to the value of the constant component of the address (for example, 192.168.0.) and the calculated value of the low-order part (for example, in the range 1-254). For example, we will assume that we need to scan computers in the address range:
    192.168.0.1 - 192.168.0.30:
    set IPTMP=192.168.0. - senior part of the address
    set /A IPLAST=1 - low part. The /A switch means a calculated numeric expression
    set IPFULL=%IPTMP%%IPLAST% - the value of the full IP address.
    The command line for PSlist will look like this:
    pslist\%IPFULL%%1
    Now all that remains is to run PSlist cyclically, adding one to the low-order part of the address in each cycle until its value reaches 30 and analyze the ERRORLEVEL value after execution. To analyze the result, we will perform the transition with the command:
    GOTO REZULT%ERRORLEVEL%
    providing a transition to the REZULT0 label when a process is detected and to REZULT1
    2013-08-25 14:35:35: Articles: Information security: Software. Did you like it?
  • Sets, removes, and views environment variables. Called without parameters, command set displays a list of set environment variables and their values.

    Syntax

    set [[/a [expression]] [/p [variable = ]] line]

    Options

    /a Indicates that the parameter line is a calculated numeric expression. /p Sets the value variable input line. variable Specifies the name of the variable whose value you want to set or change. string Sets the string value for the specified variable. /? Displays help on the command line.

    Notes

    • Using the command set in the recovery console

      Team set with other parameters is available in the recovery console.

    • Using special characters

      Symbols<, >, |, &, ^ are special shell characters, you must either precede them with a control character (^) or enclose them in quotation marks when using the characters in a parameter line(For example, " content_line & symbol" ). When you quote a string that contains special characters, the quotes are considered part of the environment variable value.

    • Using Environment Variables

      Environment variables are used to control the operation of certain batch files and programs and to control the operation of Windows XP and the MS-DOS subsystem. Team set often used in the Autoexec.nt file to set environment variables.

    • Display current environment settings

      When the team set called without parameters, the current settings will be displayed on the screen. Typically these settings include the COMSPEC and PATH variables, which are used to locate programs on disk. Two other environment variables used by Windows are PROMPT and DIRCMD.

    • Using parameters

      When you specify values ​​for a variable and a string, the value of the variable is added to the environment, and the string is mapped to that variable. If the variable already exists, the new value replaces the old value.

      If on the team set If only the variable name and equal sign are specified (no value), any value will no longer be assigned to the environment variable, which is equivalent to deleting the environment variable.

    • Usage /a

      The following table shows the operators that support the parameter /a, in descending order of priority.

      When using the logical operators (&& ||) or the remainder operator (%), enclose the string expression in quotation marks. Any non-numeric strings in the expression are considered to be environment variable names whose values ​​are converted to numbers before processing. If an environment variable name is specified that is not defined in the current environment, it is assigned the value of zero, which allows arithmetic operations on environment variable values ​​to be performed without using % to obtain the value.

      When executing the command set /a from the command line outside the command script, the final value of the expression is printed.

      Numeric values ​​are decimal numbers, except those prefixed with 0x for hexadecimal numbers and 0 for octal numbers. Thus, 0x12 is the same as 18 and 022. Octal representation requires care. For example, 08 and 09 are not valid because 8 and 9 are not octal digits.

    • Usage /p

      Used when you do not need to enable the command line.

    • Delayed environment variable expansion support

      Added support for environment variable expansion with delay. This support is disabled by default, you can enable or disable it using the command cmd /v.

    • Working with command extensions

      With command extensions enabled (default) and command running set without values, all current environment variables are displayed. If the command is executed set with a value, the variables corresponding to that value are displayed.

    • Using the command set in batch files

      When creating batch files, use the command set to create variables and use them as numeric variables from %0 to %9 . You can also use variables from %0 to %9 as input for command set.

    • Accessing command variables set from package programs

      When accessing a variable from a batch program, the variable name must be surrounded by percent signs (%). For example, if a variable BAUD is created in a batch program, a replacement parameter can be associated with it by using the name %baud% on the command line.

    Examples

    To set an environment variable named TEST^1, enter the command:

    set testVar=test^^1

    To set an environment variable named TEST&1, enter the command:

    set testVar=test^&1

    Command variable value set defines everything that follows the equal sign (=). When entering:

    set testVar="test^1"

    The result will be as follows:

    testVar="test^1"

    To set the INCLUDE environment variable so that it is associated with the string C:\Inc (the Inc directory on drive C), you can use the following command:

    set include=c:\inc

    The line C:\Inc can be used in batch files by enclosing the INCLUDE name in percent signs (%). For example, in a batch file, you can use the following command to print the contents of the directory pointed to by the INCLUDE environment variable:

    When executing the command, the line %include% will be replaced with the string C:\Inc.

    You can also use the command set in a batch program that adds a new directory to the PATH environment variable. For example:

    @echo off
    rem ADDPATH.BAT adds a new directory
    rem to the path environment variable.
    set path=%1;%path%
    set

    With command extensions enabled (default) and command running set with a value, all environment variables corresponding to the value are displayed. For example, when entering on the command line: set p, the result will be as follows:

    Path=C:\WINNT\system32;C:\WINNT;C:\WINNT\System32\Wbem
    PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
    PROCESSOR_ARCHITECTURE=x86
    PROCESSOR_IDENTIFIER=x86 Family 6 Model 8 Stepping 1, GenuineIntel
    PROCESSOR_LEVEL=6
    PROCESSOR_REVISION=0801
    ProgramFiles=C:\Program Files
    PROMPT=$P$G

    Some techniques and features of working with the Set command can be found in the section Arithmetic data processing.

    For questions, discussions, comments, suggestions, etc. you can use forum section this site (registration required).