Environment variables from the command line. Basics of BAT files


0.00 (1 )

General approach.

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

or on a specific command:

HELP Command name

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

< - redirecting input

> - redirecting output (or\u003e\u003e - redirecting to an existing file when the output is appended to the end of the file.)

To output the data stream of the commandHELP to the file help.txt the command line will be as follows:

HELP\u003e help.txt

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

HELP GOTO\u003e goto.txt

Using environment variables.

In batch files you can, and often should, use environment variables - Variables whose values \u200b\u200bcharacterize the environment in which the command or batch file is executed. The values \u200b\u200bof environment variables are generated when the OS is loaded and the user is registered in the system, and can also be set using the commandSET whose format is:

SET [variable \u003d [string]]

variable The name of the environment variable.

line The character string to assign to the specified variable.

For example the command line

SET mynane \u003d Vasya

will add the variable myname with the value Vasya.

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

will display the word time, and the command

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

And the command line

SET PATH \u003d 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 \u200b\u200bof variables to be displayed on the screen, in the form:

NUMBER_OF_PROCESSORS \u003d 1 - number of processors

OS \u003d Windows_NT- OS type

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

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

PROCESSOR_ARCHITECTURE \u003d x86 - processor architecture.

PROCESSOR_IDENTIFIER \u003d x86 Family 6 Model 8 Stepping 1, AuthenticAMD - processor ID.

PROCESSOR_LEVEL \u003d 6 - processor level (model number).

PROCESSOR_REVISION \u003d 0801 - processor version.

ProgramFiles \u003d E: Program Files - path to the "Program Files" folder

PROMPT \u003d $ P $ G - command line prompt format $ P - path for the current directory $ G - "\u003e" sign.

SystemDrive \u003d E: - the letter of the system drive.

SystemRoot \u003d E: WINDOWS - Windows OS directory.

The value of some variables is not displayed by the SET command. These are variables whose values \u200b\u200bare dynamically changed:

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

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

% TIME% - Takes the value of the current time.

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

% ERRORLEVEL% - Takes the current value of the ERRORLEVEL task completion code

% CMDEXTVERSION% - Takes the command shell version CMD.EXE for extended command processing.

% CMDCMDLINE% - Takes the value of the line that invoked the command processor.

You can use the command line to view the value of a variable:

ECHO% variable%

Input parameters for the batch file.

It is possible to pass command line parameters to a batch file and use their values \u200b\u200bin statements of the batch file itself.

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

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

ECHO< текст >

However, if the text is replaced by% 1, the first parameter will be displayed, by% 2 - the second, etc.

Create a parm.bat file with the following content:

echo First parameter \u003d% 1

echo Second parameter \u003d% 2

echo Third parameter \u003d% 3

and run it with the following command:

parm.bat FIRST second “two words”

after completing 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 OFFby placing it on the first line of the batch file. To make a line of a command file be ignored by the shell, place at the beginning of it REM< пробел > ... In this way, you can place comments, often useful in large batch files:

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

REM will only display the result of their execution.

echo First parameter \u003d% 1

echo Second parameter \u003d% 2

echo Third parameter \u003d% 3

Try to replace 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 work depending on the fulfillment of certain conditions. To illustrate the techniques for using conditional jumps, let's create a batch file, the purpose of which will be to assign a predefined drive letter to removable media, which will be used as flash drives. The conditions are as follows - there are 2 flash drives, one of which should be visible in the explorer as drive X: and the second as drive Y: no matter which uSB port they are connected. We will assume that real disks can be connected as F: or G: We will recognize disks by the presence of a file with a specific name (it is better to make such a file hidden in the root directory and call it something unusual):

Flashd1.let - on the first disk

Flashd2.let - on the second

Those. the task 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 the drive letter X: or Y:

To find a file on disk, use the commandIF EXIST:

IF EXIST filename command

The easiest command is to useSUBSTmapping a drive name to a directory.

SUBST X: C: - creates a virtual disk X: with the contents of the root directory of the C:

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

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

It is advisable to bypass the execution of SUBST if the virtual disks X: and Y: have already been created (or delete them using SUBST with the -d option before connecting). We modify the batch file usingGOTO - transfer of control to the line of the batch file by label.

GOTO label

The label must be on a separate line and start with a colon. Let's make changes in our batch file so that no error messages appear:

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

IF NOT EXIST X: GOTO SETX

REM if X exists: - go to check for Y:

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

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

REM if Y: exists - terminate 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 disappeared. Symptoms of errors during command execution 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 exited without error and 1 if an error occurred. There may be other values \u200b\u200bas well, if they are provided in the executable program.

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

ECHO Call 1.bat

ECHO Return.

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

When test.bat is executed, a message will be displayed

Calling 1.bat

and control will get 1.bat with the pause command. After starting a key on the keyboard, the command line "ECHO Return." and the screen will display

If CALL is removed in test.bat, then return from file 1.bat will not be performed. By the way, using the transfer of control to a batch file, you can organize its looping. Try adding the following line to the end of the test.bat file:

You can exit the batch file loop by pressing CTRL-Break. It is possible to use the CALL command to call a procedure within a batch file. In this case, not the name is used as an argument external fileand the label is:
....
call: proc1
....
: proc1
....
exit
....

File creation.

Windows does not have a dedicated command to create a file, but it can be easily dispensed with in several ways:

Copy from console to file

COPY CON myfile.txt

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

Redirecting output

ECHO 1\u003e myfile.txt

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

Combination of input and output redirection:

COPY CON\u003e myfile.txt< xyz

When executing this command, as in the first case, copying from the console to a file is used, but instead of data from the keyboard, input from a 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 dummy device with a name nul to the file.
copy nul myfile.txt

If you often have 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 at startup.

File contents:

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

Command line:

newfile.bat myfile.txt

Or

nf.bat myfile.txt

Or
nf myfile.txt

Here's the command nf for creating empty file at command line.

Assigning the same drive letter to a removable disk.

The challenge is to make the removable USB disk (flash drive) was always available under the same drive letter, no matter what computer it was used on and how it was connected. To solve it, we will use the already mentioned command SUBST. 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% ~ d0 variable. Create a batch file with the following content:
@echo off
subst X:% ~ d0
which means - create a virtual disk X: which is mapped physical diskfrom where the batch file was launched.
For more information on the% 0 substitution values, see the command file that reads:

@echo off
ECHO PROCESSING FILE -% 0
ECHO Date / time of creation / modification of the batch file -% ~ t0
ECHO Batch file path - "% ~ f0"
ECHO Batch File Disk -% ~ d0
ECHO Batch file directory - "% ~ p0"
ECHO Command file name -% ~ n0
ECHO Batch file extension -% ~ x0
ECHO Short name and extension -% ~ s0
ECHO Batch File Attributes -% ~ a0
ECHO Batch file size -% ~ z0

Generation of archives by date and time.

Let's solve the following problem - you 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. Startup format for creating an archive:

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

a- command to create an archive.
-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 the names and paths for RAR. For what we will use the following factors:

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

    Date obtained from variable% DATE% at standard settings regional setting looks like this:
    Mon 21.01.2005 - Day of the week (2 characters) -Space-date (10 characters)
    For example, let's create a directory with the MD command< имя каталога >.
    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 \u003d% date: ~ 3%

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

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

    Time obtained from% TIME% variable:
    14:30:59.93 - Hours, minutes, seconds, hundredths of a second.
    Hundredths are, perhaps, superfluous in the archive file name. Create a temporary variable VTIME and assign it the current time without the last 3 characters
    set VTIME \u003d% time: ~ 0, -3%
    Now VTIME \u003d 14:30:59, but the ":" sign cannot be used in the file name, so we will replace it with a period.
    set VTIME \u003d% VTIME :: \u003d.%
    Variable VTIME will take the value 14.30.59 For a file name, okay.

    Let's start the archiver:

    Now you can create a batch file with the content:

    Set VDATE \u003d% date: ~ 3%
    md c: \\% VDATE%
    set VTIME \u003d% time: ~ 0, -3%
    set VTIME \u003d% VTIME :: \u003d.%
    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 on to the domain, or using the scheduler at a specified time, and you will always have time-ordered archives of critical data available.

    Create 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: ARHIV My Documents Username Date Time

    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 \u200b\u200bof these variables and use it in a single-user version with little or no change). The contents of the batch file are annotated and shouldn't be too difficult once you've figured out the previous example:

    @echo off
    rem The FROM variable is set - where to get the data for archiving
    set FROM \u003d% USERPROFILE% My Documents
    rem The TO variable is set - where to put the archives
    set TO \u003d C: arhivMy Documents \\% USERNAME%
    rem Create a TO directory
    md "% TO%"
    rem Form the name of the subdirectory from the current date
    rem current date at default settings for Win2K - Mon 25.04.2005
    rem current date at default settings for WinXP - 04/25/2005
    rem From the current date, form the name of the subdirectory - 25.04
    rem The default Windir for WinXP is C: WINDOWS, and for Win2K it is C: WINNT
    IF / I% Windir% \u003d\u003d C: WINNT GOTO Win2K
    set vdate \u003d% DATE: ~ 0, -5%
    GOTO SetFileName
    : Win2K
    set vdate \u003d% DATE: ~ 3, -5%
    rem Let's form the name of the archive file from the current time - 12: 00: 00.99
    rem, discard hundredths of a second and replace the: character with a character. Result - 12.00.00
    : SetFileName
    set vtime \u003d% TIME: ~ 0, -3%
    set vtime \u003d% vtime :: \u003d.%
    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 ARJ archiver: arj a -r "% TO% \\% VDATE% \\% VTIME% .arj" "% FROM% *. *"
    rem When using the RAR archiver:
    rar a -r "% TO% \\% VDATE% \\% VTIME% .rar" "% FROM% *. *"

    Execution of commands on a schedule.

    There is a command line utility in WIN2K / XPAT,which 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,

    the local computer is used.

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

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

    all tasks scheduled for the specified

    computer.

    / yes Canceling a confirmation request when canceling all

    scheduled tasks.

    time The time the command was run.

    / interactive Allowing task interaction with the user,

    working on the computer during the task launch. 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

    months. If date is omitted, current day is used

    / next: day [, ...] The task will be launched 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.

    "command" Command or batch file name.

    Examples of using:

    An analogue of an "alarm clock" - pop-up windows with text reminding the current or specified user to perform some action. To send a message to the user, use the utility NET.EXE

    AT 13:50 net.exe send * Time to drink coffee

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

    AT \\ SERVER 13:45 net.exe send Server needs to be rebooted

    Viewing the list of scheduled tasks:

    Removing already scheduled tasks:

    AT 3 / DELETE - deleting task number 3

    AT / DELETE / YES - deleting all tasks

    "Control Panel" - "Scheduled Tasks" allow you to view, modify and delete 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 short and full name ("Dnscache" - short, "DNS client" - full name of the service). A service name containing spaces is 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

    Full service name can be copied from “Service” -< Имя службы > - "Properties" - "Displayed 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 in any Windows OS. In addition to starting and stopping a service, it allows you to search for a specific service on computers 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 not only to stop / start a service, but also to poll its state, startup and operation 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, but also on the 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 the computer with the IP address 192.168.0.1
    sc \\ COMP start DNSCache start DNSCache service on computer COMP
    You can get a hint on how to work with the utility by entering:
    sc /?

    Displaying the value of the ERRORLEVEL variable.

    This simple batch file will display the value of the ERRORLEVEL variable for a specific command line. First, a check is performed for the presence of at least one input parameter, and if nothing is specified, an error message is issued and exit is completed. If at least one parameter is specified, then the input parameters are considered a command line and are executed, and the ERRORLEVEL value is issued using the ECHO command. File content (I named it echoEL.bat):

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

    Launch examples:
    echoEL.bat NET SHARE
    - the NET SHARE command will be executed (display a list of shared network resources) and the ERRORLEVEL code will be issued
    echoEL.bat NET SHARE X "\u003d" C:
    - the command NET SHARE X: \u003d C: (create a shared network resource with the name X, and the path to the root directory of the C drive :) Note that the \u003d character is enclosed in double quotes.
    The above options set the correct command line. But try setting the wrong parameter for NET.EXE or a command that does not exist at all and you will see what value ERRORLEVEL will take. AND NOTE that the command line DOES actually RUN and, for example, the "echoEL.bat format A:" option will format the floppy disk in drive A :.

    Dialogue with the user

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

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

    Disadvantage this method is the impossibility of continuing the execution of a batch file in the absence of a user response, therefore very often instead of set, third party programs... One of them - CHOICE.COM Download (1.7kb).
    CHOICE displays a text message to the user and waits for one of the specified answer options (pressing keys on the keyboard). Based on the selection results, the variable ERRORLEVEL 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 \u003d 1, if N - then ERRORLEVEL \u003d 2. You can use more than 2 selection options and it is possible to set a default selection when the user has not pressed any keys for a certain time. Command line format:

    CHOICE choices] c, nn]
    / C [:] choices - Specifies acceptable choices. If not set - YN
    / N - do not display choices.
    / S - lowercase and uppercase letters are different.
    / T [:] c, nn - Default selection is "c" after "nn" seconds
    text - The string of text to be output as a request

    Let's create a batch file that demonstrates the use of CHOICE. It will respond to pressing the keys "1", "2", 3 "and" 0. "Pressing" 0 "completes, and pressing the rest - a message to the user. If nothing is pressed for 10 seconds - the end.

    @ECHO OFF
    : CHOICE
    CHOICE / C: 1230 / T: 0.10 Your option
    IF% ERRORLEVEL% EQU 4 GOTO EXIT
    echo Your choice \u003d% 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 an 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 displaying text and with automatic generation of a response after nn seconds (1-99):

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

    A more versatile method is based on pinging the loopback interface with the required number of packets. Ping for loopback interface (hostname is localhost or IP address 127.0.0.1) is performed without actual data transfer, 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\u003e nul - will delay 30 seconds

    Search for computers running an application

    To implement this script, utilities from the package are used PSTools (short description). Let's create a batch file that searches the local network for computers with a running program whose name (the initial part of the name) is specified as a parameter at startup, for example, game. If detected, a message will be sent to 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 found a process on the remote computer that matches the search criteria. The name of the process to search will be set as a parameter when starting the batch file. Let's give our batch file a name psl.bat... Starting with a parameter will look like this:
    psl.bat game
    First, you need to check if the parameter is specified on the command line at startup, and if not, we will issue a message to the user and exit. If the parameter is set, let's go to the "PARMOK" label:
    @echo off
    if "% 1" NEQ "" GOTO PARMOK
    ECHO You need to specify the name of the process to search
    exit
    : PARMOK
    Now you need to ensure consistent formation of IP addresses of computers 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 constant component of the address (for example, 192.168.0.) And the calculated value of the lower part (for example, in the range 1-254). For example, let's assume that we need to scan computers in the address range:
    192.168.0.1 - 192.168.0.30:
    set IPTMP \u003d 192.168.0. - the upper part of the address
    set / A IPLAST \u003d 1 - low part. The / A key means a calculated numeric expression
    set IPFULL \u003d% IPTMP %% IPLAST% is the full IP address value.
    The command line for PSlist will look like this:
    pslist \\% IPFULL%% 1
    Now all that remains is to run the PSlist cyclically, adding one to the lower part of the address in each cycle until its value reaches 30 and analyzing 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?
  • Sometimes it is required to form date and time variable at cmd / bat scripts windowsthe way we need, and not the way the operating system gives us.

    For example, to add this data to the log file, to fix the time or date of the event, create a file with a name in which the date or time data should appear (day, month, year, hour, minutes, skunda, milliseconds.) Yes, you never know, what are our tasks ... We connect our imagination :)

    In the next example, we see the breakdown of variables according to the templates we need.

    h- hour 2 characters (that is, the hour will be issued in as follows - 01, 02, ..., 09, ... , 12, ... 24)

    m - minutes 2 characters

    s - seconds 2 characters

    ms - milliseconds 2 characters, for some reason from 0 to 99

    dd - day 2 characters

    mm - month 2 characters

    yyyy - year 4 characters

    Example of using variables % DATE% and % TIME% in scripts cmd / bat Windows:

    @echo off
    set h \u003d% TIME: ~ 0.2%
    set m \u003d% TIME: ~ 3.2%
    set s \u003d% TIME: ~ 6.2%
    set ms \u003d% TIME: ~ 9.2%
    set curtime \u003d% h%:% m%:% s%:% ms%
    set dd \u003d% DATE: ~ 0.2%
    set mm \u003d% DATE: ~ 3.2%
    set yyyy \u003d% DATE: ~ 6.4%
    set curdate \u003d% dd% -% mm% -% yyyy%
    set curdatetime \u003d% curdate%% curtime%

    echo The current time is% curdatetime%

    In some versions Windows format issuing the date and time is different, so this script can work exactly as we need.

    In theory, in a similar way you can take parts of any variables, the point is that the format is like this:

    The first digit after: ~ is the number of the character from which we start taking the value, the second digit is how many characters to capture.

    Thus, it turns out that we can take for our needs any part, any variable of the Windows environment available to us.

    I know the following variables, the values \u200b\u200bof which we can get:

    Name
    Description
    ALLUSERSPROFILE Returns the location of the "All Users" profile.
    APPDATA Returns the default location of application data.
    CD Specifies the path of the current folder. Identical to CD command with no arguments.
    CMDCMDLINE the exact command used to run the current cmd.exe.
    CMDEXTVERSION version of the current Command Processor Extensions.
    CommonProgramFiles The location of the "Common Files" directory (usually% ProgramFiles% \\ Common Files)
    COMPUTERNAME computer name
    COMSPEC path to the shell executable
    DATE Returns the current date. Uses the same format as the date / t command. Created by the Cmd.exe command.
    ERRORLEVEL Returns the error code of the last command used. A non-zero value usually indicates an error.
    HOMEDRIVE Returns the local drive name workstationassociated with the user's home directory. Set based on the location of the main directory. The user's home directory is specified in the snap-in " Local users and groups ".
    HOMEPATH Returns the full path to the user's home directory. Set based on the location of the main directory. The user's home directory is specified in the Local Users and Groups snap-in.
    HOMESHARE Returns the network path to the user's shared home directory. Set based on the location of the main directory. The user's home directory is specified in the Local Users and Groups snap-in.
    LOGONSERVER the name of the domain controller used for authorization current user
    NUMBER_OF_PROCESSORS number of processors in the system
    OS operating system name. Windows XP and Windows 2000 appear as Windows_NT.
    PATH Specifies the search path for executable files.
    PATHEXT Returns a list of file extensions being considered operating system as executable.
    PROCESSOR_ARCHITECTURE processor architecture
    PROCESSOR_IDENTIFIER processor description
    PROCESSOR_LEVEL processor model number
    PROCESSOR_REVISION processor revision
    PROGRAMFILES path to Program Files folder
    PROMPT Returns command line options for the current interpreter. Created by the Cmd.exe command.
    RANDOM a random decimal number between 0 and 32767. Generated by Cmd.exe
    SESSIONNAME Session type. The default is "Console"
    SYSTEMDRIVE the drive on which the Windows root folder is located
    SYSTEMROOT path to Windows root folder
    TEMP or TMP Returns the default temporary folders used by applications that are available to users who are logged in. Some applications require the TEMP variable, others require the TMP variable. Potentially TEMP and TMP can point to different directories, but usually they are the same.
    TIME Returns the current time. Uses the same format as the time / t command. Created by the Cmd.exe command.
    USERDOMAIN the name of the domain that the current user belongs to
    USERNAME current username
    USERPROFILE path to the profile of the current user
    WINDIR directory where Windows is installed

    Inside the command files, you can work with the so-called environment variables (or environment variables), each of which is stored in random access memory, has a unique name, and its value is a string. Standard environment variables are automatically initialized during the boot process of the operating system. Such variables are, for example, WINDIR, which specifies the location of the Windows directory, TEMP, which specifies the path to the directory for storing temporary windows files or PATH, which stores the system path (search path), that is, a list of directories in which the system should look for executable files or files sharing (like dynamic libraries). In addition, you can 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, enclose the variable name in% characters. For instance:

    @ECHO OFF CLS REM Create variable MyVar SET MyVar \u003d Hello REM Change variable SET MyVar \u003d% MyVar%! ECHO The value of the variable MyVar:% MyVar% REM Deleting the variable MyVar SET MyVar \u003d ECHO The value of the variable WinDir:% WinDir%

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

    The value of the variable MyVar: Hello! The value of the WinDir variable: C: \\ WINDOWS

    Converting Variables as Strings

    You can do some manipulation with environment variables in batch files. First, concatenation (gluing) operation can be performed on them. To do this, you just need to write the values \u200b\u200bof the variables to be connected in the SET command. For instance,

    SET A \u003d One SET B \u003d Two SET C \u003d% A %% B%

    After these commands are executed in the file, the value of the C variable will be the string "Div2" You should not use the + sign for concatenation, as it will simply be taken as a symbol. For example, after starting the file with the following content

    SET A \u003d One SET B \u003d Two SET C \u003d A + B ECHO Variable C \u003d% C% SET D \u003d% A% +% B% ECHO Variable D \u003d% D%

    two lines will be displayed on the screen:

    Variable C \u003d A + B Variable D \u003d One + Two

    Secondly, substrings can be extracted from an environment variable using the construction % variable_name: ~ n1, n2%, where the number n1 defines 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" (symbolic representation of the current date under certain regional settings), then after executing the following commands

    SET dd1 \u003d% DATE: ~ 0.2% SET dd2 \u003d% DATE: ~ 0, -8% SET mm \u003d% DATE: ~ -7.2% SET yyyy \u003d% DATE: ~ -4%

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

    Thirdly, you can perform the procedure for replacing substrings using the construction % variable_name: s1 \u003d s2% (This will return a string with each occurrence of the substring s1 in the corresponding environment variable replaced with s2). For example, after executing the commands

    SET a \u003d 123456 SET b \u003d% a: 23 \u003d 99%

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

    SET a \u003d 123456 SET b \u003d% a: 23 \u003d%

    variable b will store the string "1456".

    Operations on Variables as Numbers

    When extended command processing is enabled (this mode is used by default in Windows XP), it is possible to treat the values \u200b\u200bof environment variables as numbers and perform arithmetic calculations with 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 specified as command line parameters and displays the resulting amount on the screen:

    @ECHO OFF REM Variable M will store the sum of SET / A M \u003d% 1 +% 2 ECHO Sum of% 1 and% 2 equals% M% REM Delete variable M SET M \u003d

    Changing variables locally

    Any changes made to the environment variables in a command file using the SET command are saved after the file is finished, but they 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 \u200b\u200bof all variables in the form in which they were before starting this file. There are two commands used for this: SETLOCAL and ENDLOCAL. SETLOCAL command defines the beginning of the region local installations environment variables. In other words, environment changes made after SETLOCAL is run will be local to the current batch file. Each SETLOCAL command must have a corresponding ENDLOCAL command to restore the previous values \u200b\u200bof environment variables. Environment changes made after the ENDLOCAL command were executed are no longer local to the current batch file; their previous values \u200b\u200bwill not be restored when the execution of this file is complete.

    Wednesday shell cmd.exe is defined by variables that control the behavior of the shell and operating system.

    It is possible to define the behavior of the shell environment or the entire operating system environment using two types of environment variables: system and local.

    System environment variables determine the behavior of the global operating system environment, and local environment variables determine the behavior of the environment in a given instance of cmd.exe.

    System environment variables are conveniently set in the operating system and are available to all Windows processes, and users with administrator privileges can modify these variables. These variables are most commonly used in logon scripts.

    Local environment variables are available when the user for whom they were created is logged in. Local variables from the registry hive HKEY_CURRENT_USER are only suitable for the current user, but define the behavior of the global operating system environment.

    List of variable types in descending order of precedence.

    1. Built-in system variables
    2. Registry hive system variables HKEY_LOCAL_MACHINE
    3. Registry hive local variables HKEY_CURRENT_USER
    4. All environment variables and paths are specified in the file Autoexec.bat.
    5. All environment variables and paths are specified in the login script (if present).
    6. Variables used interactively in a script or batch file

    In the command shell, each instance of cmd.exe inherits the environment of its parent application, and accordingly, you can change the variables in the new environment, cmd.exe, without affecting the environment of the parent application.

    Here is a list of system and local environment variables for Windows XP.

    Variable

    Description

    % ALLUSERSPROFILE%

    Local

    Returns the location of the "All Users" profile.

    Local

    Returns the default location of application data.

    Local

    Returns the path to the current folder.

    Local

    Returns the command string that started this instance of Cmd.exe.

    Systemic

    Gets the version number of the current command processor extensions.

    Systemic

    Returns the computer name.

    Systemic

    Returns the path to the executable shell.

    Systemic

    Returns the current data. Uses the same format as the command date / t... Created by the Cmd.exe command.

    Systemic

    Returns the error code of the last command used. A nonzero value usually indicates an error.

    Systemic

    Returns the drive name of the local workstation associated with the user's home directory. Set based on the location of the main directory. The user's home directory is specified in the Local Users and Groups snap-in.

    Systemic

    Returns the full path to the user's home directory. Set based on the location of the main directory. The user's home directory is specified in the Local Users and Groups snap-in.

    Systemic

    Returns the network path to the user's shared home directory. Set based on the location of the main directory. The user's home directory is specified in the Local Users and Groups snap-in.

    Local

    Returns the name of the domain controller that authenticated the current session.

    % NUMBER_OF_PROCESSORS%

    Systemic

    Specifies the number of processors installed on the computer.

    Systemic

    Returns the name of the operating system. When using Windows 2000, the operating system name appears as Windows_NT.

    Systemic

    Specifies the search path for executable files.

    Systemic

    Returns a list of file extensions that are considered executable by the operating system.

    % PROCESSOR_ARCHITECTURE%

    Systemic

    Returns the processor architecture. Values: x86, IA64.

    % PROCESSOR_IDENTFIER%

    Systemic

    Returns a description of the processor.

    % PROCESSOR_LEVEL%

    Systemic

    Returns the model number of the processor installed on the computer.

    % PROCESSOR_REVISION%

    Systemic

    Returns the revision number of the processor.

    Local

    Returns command line options for the current interpreter. Created by the Cmd.exe command.

    Systemic

    Returns an arbitrary decimal number between 0 and 32767. Generated by the Cmd.exe command.

    Systemic

    Returns the name of the drive containing the Windows XP root directory (that is, the system directory).

    Systemic

    Returns the location of the Windows XP system directory.

    System and user

    Returns the default temporary folders used by applications that are accessible by logged in users. Some applications require the TEMP variable, others require the TMP variable.

    Systemic

    Returns the current time. Uses the same format as the command time / t... Created by the Cmd.exe command.

    Local

    Returns the name of the domain containing the list of user accounts.

    Local

    Returns the name of the currently logged in user.

    Local

    Returns the location of the profile for the current user.

    Systemic

    Returns the location of the operating system directory.

    Sets, removes, and views environment variables. Called without parameters, the command set lists the set environment variables and their values.

    Syntax

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

    Parameters

    / 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 command line help.

    Notes

    • Using the command set in the recovery console

      Command set with different 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 characters in the parameter line (eg, " content_string & symbol" ). When you quote a string containing special symbols, quotes are considered part of the value of the environment variable.

    • Using environment variables

      Environment variables are used to control how some batch files and programs work and to control windows operation XP and MS-DOS Subsystems. Command set often used in Autoexec.nt file to set environment variables.

    • Displaying current environment settings

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

    • Using parameters

      When specifying values \u200b\u200bfor a variable and a string, the value of the variable is added to the environment, and the string is mapped to this variable. If the variable already exists, the new value overwrites the old value.

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

    • Using / a

      The following table lists the operators that support the parameter / a, in descending order.

      Using logical operators (&& ||) or the modulus operator (%), enclose the string expression in quotation marks. Any non-numeric strings in the expression are considered environment variable names whose values \u200b\u200bare converted to numbers before being processed. If an environment variable name is specified that is not defined in the current environment, it is assigned a value of zero, allowing arithmetic operations on the values \u200b\u200bof the environment variable without using% to get the value.

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

      Numerical values \u200b\u200bare decimal numbers, except for numbers prefixed with 0x for hexadecimal numbers and 0 for octal numbers. Thus, 0x12 is the same as 18 and 022. Octal representation requires precision. For example, 08 and 09 are invalid because 8 and 9 are not octal digits.

    • Using / p

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

    • Support for delayed environment variable expansion

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

    • Working with team extensions

      With command extensions enabled (set by default) and command execution 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 before %9 ... You can also use variables from %0 before %9 as input for the command set.

    • Accessing command variables set from batch programs

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

    Examples of

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

    set testVar \u003d test ^^ 1

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

    set testVar \u003d test ^ & 1

    The value of the command variable set defines everything that follows the equal sign (\u003d). When typing:

    set testVar \u003d "test ^ 1"

    The result will be as follows:

    testVar \u003d "test ^ 1"

    You can use the following command to set the INCLUDE environment variable so that the line C: \\ Inc (the Inc directory on drive C) is associated with it:

    set include \u003d c: \\ inc

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

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

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

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

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

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

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

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

    Did you like the article? To share with friends: