How To Add, Remove and Manage Windows Shares Network Drives From Command Line?

General information about the Windows shell.

Using variables in batch files.

Passing parameters to a batch file.

Transitions and labels.

Batch File Examples:

Own command for creating new files.

Assigning the same letter to a removable disk.

Create an archive whose name contains the date and time.

Execute only at the specified time interval.

An example of creating a user directory archive.

Change date and time for files and folders.

Start and stop Windows services on the command line.

Display the value ERRORLEVEL.

Dialogue with the user.

Delays in batch files.

Detect current version of Windows.

Search in the local network for computers running the application.

Search for computers running the application in the list based on the network environment.

Shutdown computers according to the list created on the basis of the network environment.

Search for computers on the local network.

Work with disks, files and directories.

Working with graphical applications from the command line.

Recoding text files.

Common mistakes when writing batch files.

Transitions and labels.

In batch files, you can use conditional jump commands,
changing the logic of their work depending on the occurrence of certain conditions.
As an example, let’s create a command
file whose purpose is to assign a predefined letter to
removable media.

Initial data: there are 2 removable drives, one of which should be visible in the explorer as drive X:, and the second as drive Y: regardless of which USB port they are connected to and what letters are assigned to them by the operating system. To assign drive letters, you can use the command SUBST
.
We will assume that real disks can be connected as F: or G:
Disks will be identified by the presence of a file with a specific name
(it is best to make such a file hidden in the root directory of a removable disk and name it something unusual):

Flashd1.let – on the first disc

Flashd2.let – second

So the job of the batch file is to check
availability on removable disks F:
and G:
files Flashd1.let

or Flashd2.let
and, depending on which one is present,
assign drive letter X:
or Y:

To search for a file on the disk, use the command :

IF EXIST filename command

As a command that will be executed when the condition is met, use
, which is designed to map a directory to a virtual drive.

SUBST X: C:\ –

– create virtual disk
X:, the contents of which will be the root directory of drive C:

To solve the task, we create a batch file, for example with the name setletter.bat
, with the following content:

setletter.bat


The label is a character string starting with
with a colon. Let’s make changes in our batch file so that there is no
error messages:

When executing a batch file modified in this way, the message about
error when executing SUBST will disappear.

Of course, this example is very primitive, but its main purpose is not to write an optimal command script, but to demonstrate the principles of using labels and jumps. In all subsequent examples, as far as possible, this approach is used – it is not the optimality of the source text that matters, but its maximum simplicity for understanding.

One of the most important tricks when writing complex batch files
is the analysis of the success of a particular command or program.
Signs of errors when executing commands can be tracked by analyzing
special variable
,
the value of which is formed at the end of most programs.
Normally ERRORLEVEL is zero if the program exited without errors and
unit – when an error occurs. There may be other values, if they
provided in the running program.

As a command in a batch file line, you can also use
batch file. Moreover, for transmission with a return back to the point of execution
the calling batch file is used
command CALL
. Try to create a batch file test.bat
, with the following content:


– suspend the execution of the batch file until
pressing any key.

If CALL is removed in the test.bat file, leaving “1.bat”, then the batch file 1.bat will be executed, and return to test.bat will not be performed.

The called batch file can create variables and assign them
certain values ​​that will be available for processing in the caller
file. Try changing the test.bat file like this:

The called file’s variables will be available in the calling file.

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 looping of the batch file by pressing the combination
CTRL+Break
.

The CALL instruction can be used not only to call another batch file, but also to call an internal subroutine. In this case, not the name of the external file, but the label is used as an argument:

Passing parameters to a batch file.

A very useful feature of working with batch files is
the ability to get command line parameter values ​​and use them
in operations within the batch file itself.


params.bat FIRST second “two words”

Command line options containing spaces must be enclosed in double quotes.

When processing input parameters, you need to know if they were given on the command line at all. To check for the presence of any input parameters passed
batch file, you can check if the value of the variable %1
empty, which can be done by enclosing it, for example, in double quotes, and checking the result for the presence of these quotes in a row:

REM space text

Lines starting with REM space
, are treated as comments and ignored by the shell.

Using environment variables in batch files.

When working with batch files, it is impossible to do without environment variables
– Variables whose values ​​determine the environment in which the command or batch file is executed. They are often referred to as environment variables. The values ​​taken by these variables are formed when
booting Windows, user registration in the system, start or end
some applications, and, in addition, can be set using a special
teams
SET variable = value

SETX variable = value

The first assigns a value to a variable that is valid until the end of the current command line session. The second is a permanent value.

As mentioned above, the value assigned to a variable is available for processing on the command line or in a batch file using its name enclosed in percent signs – %
. System variables allow you to get information about the hardware and software environment in which the batch file is executed, which allows you to implement its execution on different computers, regardless of their specific configuration and user settings. For example, a batch file uses the output of the contents of the system directory C:\Windows
:

DIR C:\Windows

The algorithm implemented by this batch file will be perfectly executed until it encounters a computer with Windows installed not on the C: drive, but, for example, on D: To prevent this from happening, it is advisable to use the system variable WINDIR
, which takes the path value of the system directory:

In practice, the SET command usually sets and modifies the search path for executable programs.
– environment variable PATH
.

SET PATH=C:\Windows; C:\windows\system32

This command specifies that the search for executable files will be performed in
directory C:\Windows
and, if the result is unsuccessful, in
C:\windows\system32

If necessary, execute the program, for example, myedit.exe
located in
directory C:\NewProgs
you must either specify the full path of the executable file, or make the directory with the program the current directory and use only its name. If the full path is not specified on the command line, but only the name
executable file – myedit.exe

then the file will be searched first myedit.exe
in the current directory, and if
it will not be found – in directories whose list is determined by the value of the variable
PATH. Symbol ;
is the element separator in the list of search paths.
If in the above example, the current directory is not
C:\NewProgs
, and in other directories specified by the value of the variable
PATH, no executable myedit.exe
, then an attempt to run it
will end with an error. However, if you modify the value of the PATH variable to add the required directory to it, then specifying the full path of the executable file becomes optional.
Team


will change the current value of PATH,
adding the directory C:\NewProgs to the top of the list. To add a directory to the end of the list, a slightly different construction is used:

SET PATH=%path%; C:\NewProgs

Executing the SET command without parameters allows you to get the current
environment variable values:



NUMBER_OF_PROCESSORS=1 – number of processors

OS=Windows_NT- OS type

Path=C:\WINDOWS\system32; C:\WINDOWS;C:\Program Files\Far – 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 ID.

PROCESSOR_LEVEL=6 – processor level (model number).

PROCESSOR_REVISION =0801 – processor version.

ProgramFiles=C:\Program Files – path to “Program Files” folder

PROMPT=$P$G – command line prompt format $P – path for current directory $G – sign “>”.

SystemDrive=C: – system drive letter.

SystemRoot= C:\WINDOWS – Windows OS directory.

The values ​​of some variables are not displayed by the SET command, although they are present in the system. Basically, these are variables whose accepted values ​​change dynamically:



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

%DATE% – Accepts the value of the current date.

%TIME% – Accepts the value of the current time.

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

%ERRORLEVEL% – Accepts the current value of the task completion code ERRORLEVEL

%CMDEXTVERSION% – Takes the value of the CMD version. EXE for advanced command processing.

%CMDCMDLINE% – Takes the value of the line that called
command processor.

The values ​​taken by environment variables can be expanded with
special sign – symbol “~”
, which makes it possible to obtain their partial
value, or change it by substituting some part. Practical examples of using variable expansions will be discussed below.

A detailed description of the commands with examples of their use is available in the section List of CMD Windows commands
.

CMD commands

Batch file lines may contain both commands of the
command processor CMD, and the names of executable modules (programs or batch files).


– executable file ping.exe
with parameter yandex.ru
. Extension .exe
can be omitted, and this command can be written like this:

A list of standard commands can be obtained by entering the command:

Help information on a specific command can be obtained by specifying its name as a parameter of the HELP command:

HELP Team name

In the Russian version of Windows, it must be taken into account that in the command processor environment, the characters of the national alphabet are displayed in DOS encoding, in accordance with the code page (code page) 866
. If necessary, the command

is used to switch between Windows and DOS code pages

CHCP page number


– use code page 866 (DOS)


– use codepage 1251 (WINDOWS)

Appearance of the CMD window. EXE (Windows console) can be changed with the command

The command takes 2 hexadecimal digits as arguments, specifying the background color and symbol color.


– white symbols on a black background (used by default).


– black characters on a white background.


– light yellow characters on a black background.

:/>  Как добавить ключ и значения реестра с помощью CMD


– hint for COLOR command.

Help

 $ net use /? 
net use Help
net use Help

Create an archive whose name contains the date and time.

Let’s solve the following problem – you need to create an archive of files located in the directory
C:\Program Files\FAR. The name of the archive file must consist of the current time
(hours.minutes.seconds – HH.MM.SS.rar) and placed in a new directory whose name 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
– the key that determines the archiving of subdirectories (because there are subdirectories in the source folder).

Thus, to solve the problem, you need to correctly create names and paths for RAR. For what
we use the following initial data:

  • In batch files, you can access the current date and current time – the variables %DATE% and %TIME%
  • You can create temporary variables in batch files 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 a special construction using the symbol ~
    and a numeric value that defines a group of characters from the data of the current value of the variable.

    This example, like many others in this article, is not the most optimal design from the point of view of programming, and is presented in a form that is as accessible as possible for understanding. Having gained experience in writing batch files, you can remake it, turning it into literally a couple of lines.

    The date obtained from the %DATE% variable in the default Windows 2000 regional settings
    looks like this:

    Mon 21.01.2005
    – Day of the week (2 characters) – Space (1 character) – Date (10 characters) – 13 characters in total.

    In Windows XP/Vista/7-10, there is no day of the week, which simplifies the processing of the date structure somewhat.
    To create a new directory on the command line, use the command

    MD directory name
    .

    In our example, the directory name must be obtained from the current date.
    Create a temporary variable VDATE in memory and assign a value to it
    environment variable DATE, without the first 3 characters (Mon and space) – 01/20/2016:

    On versions of Windows where the value received by the DATE variable does not contain
    day of the week (3 characters – “Mon”), the value of VDATE will not be the same as
    required. In order not to analyze the signs of the presence of this code, you can
    use another option – do not skip the first 3 characters (~3) from
    the beginning of the DATE variable string, and take 10 characters from the end of the string, specifying the number 10 with a minus sign – the same result will be, for example, the string – 01/20/2016

    set VDATE=%date:~-10%

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

    MD C:\%VDATE%

    After executing this command, a directory named 01/20/2016 will be created on drive C:

    You can do without unnecessary operators associated with the formation of the value of the VDATE variable, which I used to simplify the understanding of the structure of the generated directory name:

    MD %DATE:~-10%
    – create a directory whose name will be represented as the current date DD. MM. YYYY

    The time obtained from the %TIME% variable looks like this:

    14:30:59.93
    – Hours, minutes, seconds, hundredths of a second.

    Hundredths – this is perhaps superfluous in the name of the archive file. Therefore, we create a temporary
    variable VTIME and assign it the current time without the last 3 characters, i.e.
    skip 0 characters from the beginning and cut off 3 characters from the end. The number of skipped and clipped characters separated by a comma:

    set VTIME=%time:~0,-3%

    Now the VTIME variable is set to 14:30:59, but the colon character ( : ) cannot be used in the filename, it is a special character used in device names (drive C:\). Therefore, to get a valid file name, you need to replace the invalid character with any other, for example, a dot. To replace characters, use the sign ” = ”

    set VTIME=%VTIME::=.%
    – replace the colon character with a dot character in the VTIME variable.

    The variable VTIME will take the value 14.30.59

    rar.exe a -r C:\%VDATE%\%VTIME%.rar “C:\Program files\far\*.*”

    Now you can create a batch file with content that archives the specified directory using the date and time in the archive name:


    set VDATE=%date:~-10%

    md c:\%VDATE%

    set VTIME=%time:~0,-3%

    set VTIME=%VTIME::=.%

    rar.exe a -r C:\%VDATE%\%VTIME%.rar “C:\Program files\far\*.*”

    Such a batch file can be executed via autoload, or as part of
    script, when a user logs into the domain, or using the scheduler in
    specified time, and you will always have stock sorted by time
    archives of critical data.

    Performing any action at a given time interval.

    It’s not about running a batch file at a certain time, but
    about the execution of some part of it only at a certain interval of time,
    for example, from 10:00 to 12:00. Solving this problem will require a comparison
    current time with the specified interval. For example, let’s create a command
    a file that launches the standard Windows calculator, only if
    if it is performed in the time interval from 10:00 to 12:00. Necessary
    get the current time and check that it is no more than 12:00 and
    not less than 10:00.

    Team IF
    allows you to compare strings
    when using the format:

    IF /I string1 comparison_operator string2 command

    where comparison_operator
    takes the following values:

    EQU
    – equals

    NEQ
    – not equal

    LSS
    – less

    LEQ
    – less than or equal

    GTR
    – more

    GEQ
    – greater than or equal

    and key / I
    , if present, specifies a comparison of text strings without regard to
    register. This one is commonly used to compare text strings in
    form line1==line2
    . Comparisons are made over a common data type,
    so if strings 1 and 2 contain only digits, then both strings are converted to
    numbers, after which they are compared. Therefore, in order to solve our
    tasks to compare
    a string of the first two characters of the value of the TIME variable ( hh:mm:ss )
    with a given range :


    REM Time less than 12:00 – go to the analysis of the second condition, otherwise – exit


    if %time:~0.2% lss 12 goto tst2


    if %time:~0.2% gtr 10 goto excalc

    In a similar way, you can organize a check by date, given the fact that for this method
    comparisons need to use only numeric values ​​from variables.

    An example of creating an archive of the “My Documents” catalog.

    This batch file archives the contents of a folder
    “My Documents” of Win2K/XP/7-10 users, placing them in directories

    C:\ARHIV\My Documents\Username\Date\Time

    If you have problems with incorrect character encoding
    Russian alphabet in the names of files and directories, try using the command
    CHCP
    to change code page

    chcp 866
    – set code page 866 (DOS encoding)

    chcp 1251
    – set code page 1251 (Windows encoding)

    This batch file can be greatly reduced by removing unnecessary
    variables VTIME and VDATE, which in this example are used only to
    to make the script look more visual and easy to understand. In addition, it makes sense to use a more modern free archiver, for example – 7-Zip.

    On Windows XP/Vista/7 operating systems, the default date format is not
    contains the name of the day of the week. If there is a need to get this value
    without changing the system settings and using additional software
    software, you can use the Hindows Script Host (WSH) script.

    – create a script file to get the name of the day of the week, albeit with the name
    weekday.vbs, and containing a line to display the result of the execution
    functions WeekDayName

    An example of a batch file for getting the name of the day of the week with
    using the function WeekDayName :


    There are administrative tasks that are much easier to accomplish using WSH or Power Shell scripts rather than Windows CMD batch files.

    Change the date and time of files or folders.

    In Windows, unfortunately, there is no standard console tool for changing the date and time of creation, access and modification of files and folders. Anyone who has dealt with Unix / Linux knows that these operating systems have a simple and convenient utility
    touch
    with which you can change the last access time or file modification time to the current value or to the time value,
    given as a command line argument. If the file does not exist, the utility creates an empty file with the specified name and sets the time of creation, last modification, and last access. Therefore, often touch
    used to create empty files.

    It’s no secret that the Unix/Linux command shells are far superior in their capabilities to the Windows command line, therefore, the appearance of the UNIX Shell and Utilities package is quite understandable.
    for Windows NT and older. This package is a Windows version of the most popular Unix/Linux utilities that can be executed as console commands in the user shell environment (in the module environment sh.exe
    , included in the package) or as executable files on the Windows command line. The set includes
    more than 200 programs from the company Mortice Kern Systems (MKS)
    ,
    recommended by Microsoft as a means of migrating from Unix to Windows.

    Help on working with touch.exe
    can be obtained by running the utility with the “–help” option accepted in Unix

    In this case, the user is shown a brief hint

    Examples of using the utility touch.exe
    in Windows command line:

    touch C:\folder\myfile.txt
    – change the time of access and modification of the file C:\folder\myfile.txt to the current one. If the file does not exist, it will be created with a length of zero and the current creation, modification, and access times.

    touch C:\folder
    – change the access and modification time of the C:\folder to the current one.

    touch -f C:\ntldr C:\folder
    – change the access and modification time of the C:\folder folder to the time set for the file C:\ntldr

    touch -t 199803080102.00 C:\folder
    – set the value of the date and time of modification for the existing folder “C:\folder” – 1998, March 8, 1 hour : 2 minutes :00 seconds

    touch -t 1112.30 C:\folder
    – set for the existing folder “C:\folder” the value of date and time of modification – current date, 11 hours : 12 minutes :30 seconds

    touch -a -t 2222.20 C:\folder
    – change only the access time, the modification time does not change.

    setdate.exe -c C:\1.txt 11/22/2016
    – set the creation date for the C:\1.txt file to 11/22/2016

    setdate.exe -m C:\1.txt 11/22/2016
    – set the date of change (modification) for the file C:\1.txt to 11/22/2016

    setdate.exe -a C:\1.txt 11/22/2016
    – set the access date for the C:\1.txt file to 11/22/2016

    setdate.exe -d C:\1.txt 11/22/2018
    – set all dates to 11/22/2018 for file C:\1.txt

    In versions of Windows 10 released after 2018, it is possible to use the standard Windows Subsystem for Linux (Windows Subsystem for Linux, WSL).
    The user can install one of the Linux distributions in a Windows environment without any additional virtualization tools and use both operating systems at the same time.
    With each new release of Windows 10, the WSL subsystem becomes more powerful and convenient. More –
    Installation and examples of using the WSL subsystem in Windows 10


    Stop and start system services.

    To stop and start services from
    command line, in any version of Windows, you can use the NET command. EXE



    NET. EXE STOP

    NET. EXE START



    As a command parameter, you can use either a short or full service name
    (“Dnscache” is short, “DNS client” is the full name of the service).
    The service name containing spaces is enclosed in double quotes.
    Example of restarting the “DNS client” service

    :/>  Как добавить процент заряда батареи в статус-бар в iOS 16

    net stop “DNS client”

    net start “DNS client”


    As can be seen from the table below, for example, IP address 192.168.0.1
    corresponds to the physical address of the network adapter, equal to 00-1e-13-d6-80-00
    . If the network adapter with the given address is unavailable, then there will be no such entry in the table.

    To understand the network polling algorithm, consider the following:

    ARP address resolution is used only when transmitting data over IP protocol within the local network segment specified by the mask. So, for example, for an example with an IP address of 192.168.0.1 and a mask of 255.255.255.0, this would be the IP range from 192.168.0.1 to 192.168.0.254. Addressing any other address will be performed through the devices routing
    . Those. when executing a command

    Below is a simple example of a batch file that determines the list of enabled network devices on the local network based on the results of the PING and ARP commands.

    Working with disks, files and directories.

    The task is to determine the drive letters present in the system and write the result to a file with
    named tstdsk.txt in the current directory. You can use the execution of the command IF EXIST
    in the FOR loop for a set of letters of the Latin alphabet, i.e.
    for each drive letter, check the presence of the root directory with the command

    IF EXIST drive letter:\

    First we create an empty file:

    copy null tstdsk.txt

    This action is optional if the file does not exist, but otherwise, the results will be appended to the end of the file, and if it already had a list of drives from a previous execution of the batch file, it will be doubled. Command copy nul tstdsk.txt
    for an existing file, set the data size to zero, i.e. will make it empty.

    Finally, the batch file will look like this:

    To process files of a certain type, such as any with the extension .tmp
    mask is used – *.tmp . So, to delete all *.tmp files from the C:\TEMP directory, you can use the ERASE (or DEL ) command

    ERASE C:\TEMP\*. TMP

    DEL /Q C:\TEMP\*. TMP

    Partial names can be used in file and directory masks

    ERASE C:\TEMP\A*. TMP – delete all files with extension . TMP , whose name begins with the character “A”

    DIR *u*.* – list all files and subdirectories of the current directory that contain the character “u”
    in their names

    DIR C:\*t.* – list all files and directories in the root of drive C: whose name ends with “t”

    The task is to get a list of all directories with subdirectories on a logical drive and write the result to a text file. For recursive processing of disk directories, we will use the command FOR /R

    A simple example of deleting .tmp files from the C:\TEMP directory:

    FOR /R C:\temp\ %%i IN (*.tmp) DO del %%i

    When executing the command, it is possible to use the substitution values ​​of the loop variable to get the names of drives, folders,
    files and their characteristics. Full list of possible values ​​in case of using a variable named i

    %%~i – quotation marks (“”) are removed from the variable %i

    %%~fi – %i expands to full file name

    %%~di – only the drive name is extracted from the %i variable

    %%~pi – only the path to the file is extracted from the %i variable

    %%~ni – only the file name is extracted from the %i variable

    %%~xi – the file name extension is extracted from the %i variable

    %%~si – received path contains only short names

    %%~ai – variable %i takes the value of file attributes

    %%~ti – variable %i takes the file date/time value

    %%~zi – variable %i takes the value of the file size

    It is possible to combine several operators :

    %%~dpi – %i variable is replaced with drive name and path only

    %%~nxi – the %i variable is replaced only by the file name and its
    expansion

    %%~fsIi – the %i variable is replaced only by the full path with
    short names

    %%~ftzai – the %I variable is replaced with the string returned by
    DIR team

    Just like in the previous example, it is desirable to reset the file with the results of a possible previous run of this batch file:

    As a result of executing this batch file, the file dirlist.txt will be created in the root of drive C:, containing a list of directories on the drive.

    If the FOR /R command loop uses substitution values ​​for the %%I variable, then you should not use the dot character as the set (in).

    The task is to find files with the .log extension on the disk and copy them to a directory on another logical drive – D:\MUSOR

    It is advisable to check the existence of the D:\MUSOR directory and, if necessary, create it with the command
    md
    , and also delete all files from it, if they exist, with the command del
    . Then go to the root directory of drive C: and search for files by mask *.log in the FOR command loop
    in all subdirectories.

    REM prepare directory D:\MUSOR

    if not exist D:\MUSOR md D:\MUSOR

    REM delete without confirmation ( /Q) all files from the directory

    del /Q D:\MUSOR\*.*

    REM go to the root of drive C:

    cd c:\

    REM Check for *.log files and copy them to

    REM D:\MUSOR

    for /R %%i in (c) DO (

    if exist “%%~dpi*.log” copy “%%~dpi*.log” “D:\MUSOR\*.*”

    )

    The practice of using FOR /R has shown that it is not worth using the “dot” character as a set for processing ( construction in (.)
    ) because when using substitution values, you can return from the current directory to the level above. In this example, any non-official character is used as the in set. The copy command ( copy ) can be replaced by the file move command (MOVE), which will remove the source files after copying to the D:\MUSOR directory.

    The example of copying files with the .log extension discussed above has some
    significant disadvantages – hidden files and folders are not processed, and in the final directory,
    where the files are copied to ( D:\MUSOR ) subdirectories with the same names that belong to the paths of the original copied files are not created. To eliminate these shortcomings, you can use a slightly different script:

    To copy, use the command xcopy
    with keys:

    / H
    – copy hidden files.

    /R
    – permission to replace files with “Read Only” attribute

    /Q
    – do not display names of copied files

    / Y
    – allow overwriting existing files.

    Command hint XCOPY
    can be obtained by entering:

    help xcopy

    xcopy /?

    While processing line xcopy “%%~dpi*.log” “D:\MUSOR%%~pi*.*” /H /R /Q /Y
    in the FOR loop, C:\current path\*.log will be selected as the copy source
    and as a destination – D:\MUSOR\current path\name of the copied file

    A similar approach can be used to locate and copy executable files (*.exe) from the temporary directory specified by the TEMP variable. It can be useful for finding malware.

    When working with the contents of directories, it is convenient to use the commands to remember the current directory and move to a new one PUSHD
    and commands to restore the previously stored current directory POPD

    Working with Windows graphics applications.

    Let’s say you need to run notepad.exe from the same batch file
    and cmd.exe. If you just insert lines

    notepad.exe

    cmd.exe

    then after starting notepad.exe, the execution of the batch file will pause and until
    notepad will terminate, cmd.exe will not run. The easiest way to get around this
    problem – use the standard Windows command
    . Full usage help can be obtained from:

    start/?

    Try creating a batch file with the following content:

    start /MAX notepad.exe

    start “This is CMD.EXE” /MIN cmd.exe

    net send %COMPUTERNAME% NOTEPAD and CMD running.

    After executing this batch file, you will see the started ones, in the maximized window
    (key /MAX) notepad, in a minimized window (key /MIN) command processor CMD. EXE and
    net.exe message box. Standard cmd.exe window title changed to text
    “This is CMD.EXE”. Note that the window title can be omitted, but
    peculiarity of processing input parameters by the start command can lead to
    unexpected results when you try to run a program whose name or path contains
    space(s). For example, when you try to run the following command:

    start “C:\Program Files\FAR\FAR.EXE”

    Due to the presence of a space in the path to the executable file,
    string to run FAR. EXE must be enclosed in double
    quotes, but the format of the input parameters for start
    assumes a header
    window, also enclosed in double quotes, resulting in “C:\Program Files\FAR\FAR.EXE”
    is interpreted not as an executable program, but as a window title.
    In order to prevent this from happening,
    use any, even empty, title:

    start “” “C:\Program Files\FAR\FAR.EXE”

    If you still need advanced application window management,
    you will have to use third-party software, for example, the well-known utility cmdow.exe

    Version of cmdow.zip used in this article.
    ZIP archive, password protected novirus

    Due to its specific behavior, this utility is defined by most antiviruses as
    as a virus, so for normal operation you need to add it to the antivirus exceptions. And for the same reason, the program archive is password protected novirus

    Cmdow.exe is a tiny utility that works on all versions of Windows and doesn’t require installation.
    Allows you to get a list of windows, move, resize, rename,
    minimize/maximize, activate/deactivate, close, hide windows
    applications and more. Help can be obtained by command:

    cmdow /?

    Approximately 30 keys are used. Description in Russian you will find
    here.

    Some examples:

  • Getting information about windows:
  • cmdow.exe
    or cmdow.exe > wins.txt
    – display information about all windows on the screen or in the file wins.txt

    cmdow /T
    – give information about the windows displayed on the panel
    desktop tasks.

    Information contains columns:

    Handle – window handle – a hexadecimal number associated with the given window.

    Lev – window level. An application can be multi-windowed with multiple levels of windows.

    Pid is the ID of the process that spawned the window.

    -Window status- – window status (visible – Vis, hidden – Hid, active – Act,
    collapsed – Min etc.

    Image – the program that called the window.

    Caption – window title

  • Window manipulation.
  • If you want your batch file to run invisibly,
    add the line to it:

    cmdow @ /HID
    – hide the current window

    Below is a commented batch file demonstrating how cmdow works:
    It works as follows. From the CMDOW output is taken
    first, second and 8th fields.
    The first is the window handle (Handle), the second is the level (Lev), the third is the name
    programs (Image). In a cycle
    cmdow is executed and if its output contains a line where the name
    IEXPLORE program and window level 1 is running cmdow /END
    .
    While this batch file is running, launch “Internet Explorer” is not
    succeed. And if you add “cmdow @ /hid” to the beginning of the batch file, then it will be
    its window is also hidden.

    Recoding text files.

    In this example, you need to convert the source text file in DOS encoding
    into a new text file in Windows encoding.
    Change is used as a conversion mechanism
    code page command CHCP

    and output the contents of the source file line by line with the command ECHO
    With
    redirecting the output to a new file. For DOS encoding, use
    code page 866, for Windows encoding – 1251. In the example, the source file
    is called 866.txt and the file with recoded data is 1251.txt

    :/>  Как узнать ram своего компьютера windows 7

    A kind of modern standard program for transcoding
    files is considered a Unix ported utility iconv

    (as part of the libiconv library).

    When option -c is given
    , characters that cannot be converted simply
    are thrown away. Otherwise, when such an error occurs, the program
    terminates abnormally.

    When option -s is given
    , no error messages are displayed.

    Key -l
    allows you to get a list of available encodings. The utility allows
    transcode text, practically, from any encoding to any.

    Common mistakes when writing batch files.

    • The manual batch file runs successfully, but the one run with the scheduler does not work.

    Usually, this is because you don’t take into account the fact that when your batch file is executed, the environment variables may be quite different than when it was written and run from the command line. For example, a batch file uses the launch of the myprog.exe application located in the SCRIPTS directory on the D: drive. If the batch file uses the name of the executable module without the full path

    MYPROG. EXE

    and if the directory D:\SCRIPTS is not registered in the search paths (PATH variable), then the MYPROG. EXE can only be found and executed if the current directory is D:\SCRIPTS. But if you specify the full path to myprog.exe:

    D:\SCRIPTS\myprog.exe

    then the program will be found and executed anyway.

    In addition, often the program specified in the batch file uses its own directory to search for its components (dll, ini, etc.). But at the time of its execution, the current directory can be any (most often, the Windows system directory). Naturally, the components are not found and the program is not executed. To fix the problem, add commands to the batch file to navigate to the correct directory. For example, the program myprog.exe should run in the directory D:\SCRIPTS:

    Rem Change the current disk

    D:

    Rem go to SCRIPTS directory

    CD D:\SCRIPTS

    myprog.exe

    You can also use the commands pushd to navigate through directories
    and popd
    , which are described and used in the section List of CMD Windows commands
    .

  • Russian names of files, services, etc. are displayed incorrectly.

    The reason is that when you create batch files, you
    used a text editor in which Russian characters are represented
    not in DOS encoding. If in the above example of restarting the “DNS Client” service
    you are using the wrong encoding, the Russian part of the service name will not be recognized
    due to incorrect encoding and a message will be displayed that the specified service is not
    installed. To avoid problems with Russian characters in batch files,
    use a DOS-encoded editor, such as the built-in editor
    file manager Far Manager. Switching between encodings in the editor is done by pressing F8
    . With FAR, you can easily transcode by copying (cutting) the text to the clipboard, then
    pressing F8 and pasting the text from the clipboard.


  • Own command for creating new files.

    There is no special command for creating a new file as part of the Windows operating system, but you can easily do without it in several ways:

    Keyboard copy to file

    COPY CON myfile.txt

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

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

    Combination of input redirection and output redirection:

    COPY CON > myfile.txt < xyz

    When executing this command, as in the first case, copying is used
    from the console to a file, but instead of manually entering data from the keyboard, input is used with
    non-existent file (device) xyz. The system will display a message stating that such
    device or file
    does not exist, but an empty file myfile.txt will be created successfully.

    Usually, copy command from dummy device nul is used to create an empty file
    to file. Using the nul device allows you to bypass standard I/O operations that are not actually performed on it. Copying from a dummy device to a file will create an empty file without any error messages.

    COPY NUL myfile.txt

    When working on the command line, you often need to create new empty
    files, therefore, it is worth preparing your batch file (for example, with
    named nf.bat),

    and pass the name of the newly created file to it as a parameter when
    startup.

    For ease of use, you can place this batch file in the system directory
    (for example, in C:\windows\system32) or any other that exists in the paths
    searches specified by the value of the PATH variable). Now, in the command line, being in any directory, you can create empty files with one command.

    The ability to create files in system directories depends on the system security settings and the rights of the user under whose account context the command is executed. Many commands can only be executed by a user with administrator rights.

    The batch file extension (.bat) can be omitted and the command is further simplified:

    In the text of the batch file, there is a check whether the name is set
    created file on the command line (if “%1%” EQU “” goto error), and if not
    given – an error message is displayed and the batch file exits
    my job.

    In terms of improving the functionality, you can add a check to this batch file
    on the existence of a file with the name specified on the command line and a warning to the user about its possible overwriting.

    Create Share

     $ net share "myshare=c:\cygwin64" 
    net use - Create Share
    net use – Create Share

    Examples of batch files.

    The use of command line utilities and batch files often allows
    solve many problems associated with the daily operation of a computer
    technology. Most system administrators and knowledgeable users
    continue to use them, despite the fact that something new appeared in Windows,
    more powerful and modern system management tool – WMI

    (Windows Management Instrumentation) and multifunctional user shell Power Shell
    . Obviously, last but not least, this
    due to the ease of implementation and sufficient
    command line efficiency for day-to-day system maintenance tasks.

    Below are simple
    examples with comments that demonstrate some of the features and
    ways to use .cmd and .bat

    Delete or Remove Share From Remote Computer

     $ net share myshare \\192.168.122.66 /delete 

    Set Permission For Share Access

     /GRANT:username,right 
     $ net share myshare myshare /GRANT:john,FULL 

    Assigning the same drive letter to the removable disk.

    The task is to make the removable USB disk (flash disk) available
    always under the same letter, no matter what computer it is on
    used and how it was connected. To solve it, we use the command already mentioned above SUBST
    , but we implement the assignment of a new drive letter with
    using a substitution variable %0
    created
    system every time the batch file is run.

    Select the desired letter for the removable disk, for example – X.

    Some of the environment variables, including the variable %0
    ,
    taking the value of the path and name of the executing batch file, allow
    with a certain modification using a special feature –
    character ” ~ ”
    , get its partial value (variable expansion). For example, not the full path
    file, but only its name, or location directory, or drive letter, with
    which it was launched or about a dozen different elements related to
    with substitution variable values ​​ %0
    .

    Additional insight into wildcard values
    variable %0 can be obtained from the batch file as follows
    content:

    List Shares

     $ net share 
    List Shares with net use
    List Shares with net use
    • Share name
      is the name used to mount this share in the client side
    • Resource
      is the path the share will be mapped
    •   Remark
      is comments and notes about this share which is set while share creation.

    Unmount Share

     $ net use z: \\192.168.122.167\myshare /delete 

    Delete or Remove Share With Physical Location

     $ net share c:\cygwin64 /delete 

    Syntax

     net use [option] 

    CMD Special Characters

    Working with a command processor involves the use of two standard devices – an input device (keyboard) and an output device (display). However, it is possible to change the default I/O devices using special characters – redirect characters


    – output redirection


    – input redirection

    To display help not on the screen, but, for example, in a file called help.txt, you can use the following command:

    HELP > help.txt

    When this command is executed, a file with the name help.txt will be created in the current directory
    , whose contents will be the output of the HELP command. If file help.txt
    existed at the time the command was executed, its contents will be overwritten. In order to append data to the end of an existing file, doubling the output redirection character is used – “>>”

    HELP GOTO > myhelp.txt

    – to file myhelp.txt
    help will be displayed on the use of the GOTO command

    HELP COLOR >> myhelp.txt

    – help on using the COLOR command will be added to the end of the myhelp.txt file

    The simplest example of input redirection:

    cmd.exe < commands.txt

    – the command processor will not wait for commands from the keyboard, but reads them from the file commands.txt
    . In fact, the specified text file in this case is a batch file.

    When running the shell, you can specify a specific command as a command line argument:

    cmd.exe /C HELP FOR

    – execute command HELP FOR
    and terminate (command line parameter or switch /C
    )

    cmd.exe /K HELP FOR

    – execute command HELP FOR
    and switch to the waiting mode for further input of commands (key / K
    )

    Detailed help on using cmd.exe can be obtained by entering the key /?

    &
    – a single ampersand is used to separate multiple commands on the same command line.

    team1 & team2
    – the first command is executed, then the second command.

    &&
    – a double ampersand between two commands, meaning the conditional execution of the second command. It will be executed if the exit code (or return code) of the first command is zero, i.e. command completed successfully. success
    command execution is determined by the value of the special environment variable ERRORLEVEL.

    team1 && team2
    – running command1
    , a

    team2
    executed only if the first one was successful.

    The command following the concatenation characters does not need to be enclosed in
    double quotes, otherwise the shell will double them and report an error.
    Command Line Execution

    cmd.exe /C “HELP IF” & ”HELP IF”


    Will end with the execution of the first command and an error message for the second:

    “HELP” is not internal or external
    command, executable program, or batch file.

    Like any other programming language, CMD scripts cannot do without variables. To obtain their value, a special symbol is used – the percent sign %
    . A string enclosed in percent signs is interpreted as the value of a variable, for example:

    Symbol ^
    , which is the last character of the line, is used as a sign of continuation of the previous one. This applies to both text and commands.

    Delete or Remove Share With Share Name

     $ net share myshare /delete 
    Delete or Remove Share
    Delete or Remove Share

    Mount Share

     $ net use z: \\192.168.122.167\myshare 
    Mount Share with net use
    Mount Share with net use

    List Mounted Shares

     $ net use 
    List Mounted Shares with net use
    List Mounted Shares with net use
    • Status
      shows current situation like connected or not connected
    • Local
      shown the local mount point
    • Remote
      shows remote file share full path including the host name/IP address and the path
    • Network
      shows network used to access share.