This article will cover the basics command line Windows, namely:

  • Command line concept;
  • Shell Commands Reference;
  • Sequence of events when executing a command;
  • Creating command line scripts;
  • Controlling the display of text and commands;
  • Commands for studying system information;
  • Commands for using the registry;
  • System services management;
  • Reboot and shutdown systems from the command line;
  • Manage applications and processes from the command line.

Command Line Concept

Command line support is built into the operating system Microsoft Windows and is accessible through a command shell window. The Command Prompt is supported in all versions of Windows and is used to run built-in commands, utilities, and scripts. Despite the power and flexibility of the command line, some Windows administrators never use it. If you have enough graphical administration tools, you can only use them by clicking the user interface elements.

However, experienced Windows administrators, qualified software specialists technical support and “advanced” users cannot do without the command line. Knowing how to properly use the command line—specifically, which command line tools to choose and how and when to use them so that they work effectively—can help you avoid many problems and ensure smooth execution of your operations. If you support multiple domains or networks, understanding time-saving ways to work with the command line is not only important but necessary to automate daily operations.

With each new version Windows command the line was improved and its capabilities expanded. The command line has undergone significant changes, associated not only with increased productivity, but also with increased flexibility. Now you can use the Windows command line to solve problems that could not be solved in previous versions Windows.

Start the Windows command shell environment different ways, in particular by specifying parameters when starting Cmd.exe or using your own start file stored in the directory %SystemRoot%\System32.

Additionally, the command line can be run in batch mode to execute a set of commands. In batch mode, the command line reads and executes commands one after another.

Working with the team Windows string You must understand where the commands you use come from. “Native” commands (built into the operating system) come in two types:

  • Domestic– exist inside the command shell, they do not have separate executable files;
  • External- implemented in separate executable files, which are usually stored in the %SystemRoot%\System32 directory.

Quick reference to shell commands (Cmd.exe)

  • assoc- displays or modifies mappings ( associations) file types;
  • break— sets breakpoints when debugging
  • call— calls a procedure or another script from a script;
  • cd (chdir) - shows the name of the current directory or changes the current directory;
  • cls— clears the command line window and screen buffer;
  • color— sets the text and background colors of the command shell window;
  • sorry— copies files or performs file concatenation;
  • date— shows or sets the current date;
  • del (erase) — deletes given file, a group of files or directory;
  • dir— shows a list of subdirectories and files in the current or specified directory;
  • echo— displays text in the command line window or sets whether commands should be displayed on the screen (on|off);
  • endlocal— marks the end of localization ( local scope) variables;
  • exit— exit the command line shell;
  • for— executes the given command for each file in the set;
  • ftype Lists or changes current file types in file extension mappings to programs;
  • goto— specifies that the command interpreter should go to the line with the given label in the batch script;
  • if— executes commands according to conditions;
  • md (mkdir)— creates a subdirectory in the current or specified directory;
  • move— Moves a file or group of files from the current or specified source directory to the specified directory. Can also rename a directory;
  • path— shows or sets the command path used by the operating system when searching for executable files and scripts;
  • pause- stops execution batch file and waits for keyboard input;
  • popd— makes current the directory whose name was saved by the PUSHD command;
  • prompt— specifies what text should be shown in the invitation line;
  • pushd— saves the name of the current directory and, if necessary, makes the specified directory current;
  • rd (rmdir)— deletes a directory or a directory along with its subdirectories;
  • rem— marks comments in a batch script or Config.nt;
  • ren (rename)— Renames a file or group of files;
  • set— shows the current environment variables or sets temporary variables for the current command shell;
  • setlocal— marks the beginning of localization ( local scope) variables in batch scripts;
  • shift— shifts the position of replaced parameters in batch scripts;
  • start— launches a specified program or command in a separate window;
  • time— shows or sets the system time;
  • title— sets the title of the command shell window;
  • type— shows the contents of a text file;
  • verify— turns on the mode for checking files after writing to disk;
  • vol- shows the label and serial number disk volume.

Any syntax internal team (and most external) can be obtained by entering the command name and /? at the command line, for example:

Command shell- a very powerful environment for working with commands and scripts. You can run commands on the command line different types: built-in commands, Windows utilities and command line versions of applications. Regardless of the type, every command you use must follow the same syntax rules. According to these rules, the command name is followed by required or optional arguments. Additionally, arguments can use input, output, or standard error redirection.

Sequence of events when executing a command

  • The command shell replaces any variables entered in the command text with their current values;
  • If a group or chain of several commands is entered, the line is split into individual commands, which in turn are split into the command name and arguments. Next, the commands are processed separately;
  • If a command name specifies a path, the shell looks for the command in that path. If there is no such command in the specified directory, the shell returns an error;
  • If the command name does not include a path, the shell first tries to resolve the command name to internal level. If an internal command with the same name is found, then an internal command has been called and can be executed immediately. If there is no internal command with the same name, the shell first looks for the command executable in the current directory, and then in the directories listed in environment variable PATH. If the command file is not in any of these directories, the shell returns an error;
  • If the command is found, it is executed with the given arguments and, if necessary, input is read from the source specified in those arguments. Command output and errors are shown in the Command Prompt window or sent to a specified output and error sink.
  • As you can see, many factors affect command execution, including command paths, I/O redirection, and grouping or chaining of commands.

When working with a command shell, you probably started it by opening Start menu (Start) and selecting Programs ( Programs) or All Programs ( All programs), then Accessories ( Standard) and Command Prompt ( Command line). Other ways to start the command line are the Run dialog box ( Starting the program) or entering cmd in another, already open window command shell. These methods allow you to specify arguments when starting the command line: keys that control the operation of the command line and parameters that initiate execution additional commands. For example, you can start a command shell in silent mode ( i.e. disable echo output) with the cmd /q command or to make the command shell execute the given command and exit - to do this, enter cmd /c, followed by the command text in quotes.

The following example starts a command shell, runs the ipconfig command, outputs the results to a file, and exits:

Cmd /c "ipconfig > c:\ipconfig.txt"

Creating Command Line Scripts

Command Line Scripts- text files with commands that you want to execute. These are the same commands that are usually entered in command shell Windows. However, instead of typing commands every time you need them, you can create a script to do so and make your life easier.

Because scripts consist of standard text characters, they can be created and edited in any standard text editor, say, in Notepad ( notebook). When entering commands, make sure that each command or group of commands that must be executed together is marked with new line. This will ensure they are executed correctly. When you've finished creating the command line script, save the script file with a .bat or .cmd extension. Both extensions work the same. For example, if you need to create a script to display the system name, Windows version, and IP configuration, include the following three commands in the SysInfo.bat or SysInfo.cmd file:

Hostname ver ipconfig -all

Controlling the display of text and commands

Team ECHO serves two purposes: to write text to output ( for example, to a command shell window or a text file) and to enable/disable command echo display. Typically, when you run script commands, the commands themselves and the output of those commands are displayed in a console window. This is called command echoing ( command echoing).

To use the ECHO command to display text, type echo followed by the text you want to display:

Echo The system host name Is: hostname

To control echoing of commands using ECHO, type echo off or echo on, for example:

Echo off echo The system host name is: hostname

To direct output to a file rather than to a shell window, use output redirection, for example:

Echo off echo The system host name is: > current.txt hostname » current.txt

Now let's see how command echoing is suppressed. Start a command shell, type echo off, then other commands. You will see that the command prompt is no longer displayed. Instead, only what is typed in the console window and the output of executed commands appears. In scripts, the ECHO OFF command disables command echoing and the command prompt. By adding the ECHO OFF command to your scripts, you prevent your shell window or file from becoming cluttered with command text if you are only interested in the output from those commands.

Studying system information

Often, when working with a user's computer or a remote server, there is a need to obtain basic information about the system, such as the name of the user registered in it, the current system time or location specific file. Commands that collect basic system information include:

  • NOW- displays the current system date and time in 24-hour format, for example Sal May 9 12:30:45 2003. Available only in Windows Server 2003 Resource Kit;
  • WHOAMI— reports the name of the user registered in the system on this moment, for example adatum\administrator;
  • WHERE— searches for files using a search pattern ( search pattern) and returns a list of matching results.

To use NOW or WHOAMI, simply type the command in the command shell window and press Enter. The most common syntax for WHERE looks like this:

Where /r base_directory_file_name

Here the /r option is specified for a recursive search starting from specified directory(base_directory) and including all its subdirectories, and file_name is the full or partial name of the searched file, which may include wildcards: the ? replaces one character, and the * sign replaces a group of characters, for example data???.txt or data*.*. The following example searches the C:\ directory and all its subdirectories for all text files, whose names begin with data.

Where /r C:\data*.txt

You can also find files of all types whose names begin with data:

Where /r C:\data*.*

Sometimes you need to obtain information about the system configuration or the system environment. On mission-critical systems, this information can be saved or printed for reference. Listed below are commands that allow you to collect information about the system.

  • DRIVERQUERY- displays a list of all installed drivers devices and their properties, including module name, display name ( display name), driver type and build date ( driver link date). All information display mode (/V) reports the status and state of the driver, startup mode, memory usage information, and path to file system. The /V option also turns on detailed information about all unsigned drivers.
  • SYSTEMINFO- issues detailed information system configuration, including version, type, and manufacturer information operating system, processor, BIOS version, memory size, regional settings, time zone, and network adapter configuration.
  • NLSINFO- Displays detailed regional information, including default language ( default language), code Windows page, time and number display formats, time zone and installed code pages. This command is only available in the Windows Server 2003 Resource Kit.

To use these commands on local computer, simply type the name of the desired command in the command shell window and press Enter.

Commands for using the registry

The Windows Registry stores configuration information for the operating system, applications, users, and hardware. This data is contained in sections ( keys) and parameters ( values) registry, which are located in a specific root section ( root key), which controls how and when sections and parameters are used.

If you know the paths to the partitions and understand the allowed data types in the partitions, you can use the command REG to view sections and parameters and manipulate them in a variety of ways. REG supports several subcommands:

  • REG add— adds a new subsection or element to the registry;
  • REG delete— deletes a subsection or element from the registry;
  • REG query— displays a list of section elements and subsection names ( if they are);
  • REG compare— compares subsections or registry elements;
  • REG I'm sorry— copies a registry element to the specified partition path on a local or remote system;
  • REG restore— writes previously saved subsections, elements and parameters to the registry;
  • REG save— saves a copy of the specified subkeys, elements and registry settings to a file.

System Services Management

Services provide key functions workstations and servers. To control system services on local and remote systems, use the service controller command ( service controller command) S.C., which has a set of subcommands, only part of them is described below:

  • SC config— setting up accounts for registering and running services;
  • SC query— displaying a list of all services configured on the computer;
  • SC qc— displaying the configuration of a specific service;
  • SC start— starting services;
  • SC stop— stopping services;
  • SC pause— suspension of services;
  • SC continue— resumption of services;
  • SC failure— specifying actions to be performed when a service fails;
  • SC qfailure- View actions taken when a service fails.

You can specify a name in all commands remote computer, whose services you want to work with. To do this, insert the UNC name or IP address of the computer before the subcommand you are using. Here's the syntax:

Sc ServerName Subcommand

Reboot and shutdown systems from the command line

Systems often have to be rebooted or shut down. One way is to use the Shutdown utility for this, which allows you to work with local and remote systems. Another way to control system shutdown or reboot is to assign a shutdown task. Here you can use Schtasks to specify a shutdown time, or create a script with a list of shutdown commands for individual systems.

The following commands allow you to control the reboot and shutdown of the local system.

Shutting down the local system:

Shutdown /s /t Shutdown Delay /1 /f

Shutdown /r /t Shutdown Delay /1 /f

Application, process and performance management

Whenever the operating system or user starts a service, application, or command, Microsoft Windows starts one or more processes to manage the associated program. Several command line utilities will make it easier for you to monitor and manage programs. These utilities include:

  • Pmon (Process Resource Manager) - Shows performance statistics, including memory and CPU usage, and a list of all processes running on the local system. Allows you to receive detailed " pictures» resources involved and processes performed. Pmon comes with the Windows Resource Kit;
  • Tasklist (Task List) - lists all running processes by name and process ID, reports information about the user session and occupied memory;
  • Taskkill (Task Kill) - stops the execution of a process specified by name or identifier. Using filters, you can stop processes depending on their state, session number, CPU time, memory footprint, user name, and other parameters.

That's basically all I wanted to tell you about the basics of the Windows command line.

The monster must die

I do not consider myself an IT specialist or an orthodox user.
Internet or crazy gamers, but I have a computer, I work with
certain software and monitor computer information
situation in the world. First of all, due to the fact that we live in a post/information age,
globalized world, where computers control nuclear power plants, military
strategic objects, and may the inveterate forgive me
Slavophiles, the thinking of the majority of the population. Impact on high-tech
The sphere of post/society is determined by the impact on humanity as a whole. Especially if
this influence is exerted by the monopolist.

Monopoly on operating systems, and if expressed without techno-monocultural
vulgarities, monopoly on successful imitations artificial intelligence, leads
to a certain political instability. Science fiction writers, prophecies of our
time, have repeatedly predicted a future in which large corporations
were endowed with political powers. Well, when some system
interacts with most reasonable users, and at the same time belongs to
(submits to) a narrow circle of people, we can predict various options
developments of events. We even have the opportunity to rely on a real prototype,
if we take Microsoft Corporation as a basis. The well-known brainchild of Paul Allen and
Bill Gates has been fighting off accusations of monopolism since back in 1990.
Then the US Federal Trade Commission arranged
checking for possible collusion between Microsoft and IBM. Investigation
died out, but in 1993 Microsoft's marketing policies related to
The US Department of Justice became interested in the spread of DOS. In 1994
an amicable agreement is reached between Microsoft and the Department of Justice, according to
the terms of which Microsoft is prohibited from using its already dominant
market position to suppress competitors. Next year the Ministry
blocks plans to merge Microsoft and Intuit - again from
antitrust considerations. In August 1997, Microsoft arranged a donor
an injection of $150 million into its competitor, Apple Computers. These and
Some of Microsoft's other actions are causing the Justice Department the most
bad suspicions. Two months later, the Department of Justice files a lawsuit against
Microsoft demanding a daily fine of 1 million to the corporation
dollars for violating the 1994 agreement. And so on and so on many times
times, with varying degrees of success, Microsoft moved toward its current leadership
positions. The last antimonopoly trial took place outside the territory
USA, in the European Union. A specially formed commission threatened with a fine of up to $3.2
billion, if the Company does not open the program code for research, and also does not
will exclude Media Player included with the Windows operating system. However, according to
According to European Commission spokesman Tilman Luder, “Microsoft is unlikely to have to
open Windows program code. The company will only have to provide
"protocols" that will allow competitors to create Windows-compatible
software products."

Microsoft, having somewhat ambiguously interpreted the decision of the EU Commission,
offered to open source Windows Server 2003 and provide documentation
with a description of protocols under certain licenses, which, of course, need to
will buy. It is unclear whether European officials will be satisfied with the new
Microsoft offers. EU representatives have already stated that they will carefully study it
statements. However, it is possible that the conflict between the EU and Microsoft will not end here.
since the American corporation and European structures are also arguing about the price
licenses to use Windows code. In addition, the authors of the lawsuit against Microsoft
believe that the latter has no right to take money for network licenses
protocols because it is standard software, encrypted for
countering competitors. The corporation itself, however, claims that speech
is about unique developments.

Pot of honey

What, in fact, do all these “antitrust” processes achieve, in addition to
Surely there are limitations to the company's growth? First, force Microsoft to release
limited Windows version, from which suppliers could completely throw out
any application program that in one way or another “infringes” the interests of competitors –
all sorts of multimedia utilities, like Windows Media Player or Internet Explorer.
Second, order Microsoft to provide competitors with everything they need
technical information so that their software can work without glitches with Windows.
Third, open the source code of the entire operating system for careful study.

Now let's take a closer look at opening the source code of Windows.
Both competitors and open source developers would really like to take a look at it
community, and, quite likely, hackers ;). These are the last ones at Microsoft, apparently
feared the most. Microsoft representatives have repeatedly stated that
openness is not an advantage, as Linux proponents claim, but
terrible danger: they say, anyone can find the hole they need, and
use it for evil - write a virus, or arrange a hack. Therefore it's better
hide the source codes, along with all their holes. Let me remind you that in the community
It is customary for open source programs to inspect codes, identify errors, report them, and
try to patch up. Who cares? Thoughts have been repeatedly expressed about
that there are such flaws in the Windows source code that opening them means
really put at theoretical risk all those who use the products
Microsoft. Most likely Microsoft Windows in all its versions contains
a vulnerability that cannot be fixed (according to some third parties)
researchers in different versions similar Absolute Errors are different). Treat her
about the same as filling a hole in the middle of a foundation that is already
there is a multi-storey building. Of course, Microsoft is well aware of
the presence of an Absolute Error, but do not consider it a vulnerability. Of course, because the original
The codes are still hidden from the public eye.

Let's slow down a little and give the Company its due. She has been for several years now
provides source code to authorities in many countries, including
Russian Federation. The fact of providing access to Windows source code is very
important because this software serves as a platform based on
which built the state information systems of many countries, as well as
and defense systems (and you thought there were superaxes everywhere on Linux based? :)).
Agreements not only provide access to source code Windows
and other important technical information, but also joint work, as well as
consultations in order to adapt the operating system to the requirements that
presented by the state to information systems used in organs
state power. Provision of source codes and
detailed technical documentation as part of the GSP (Government Security
Program) is a stunningly brilliant move to assert Microsoft's monopoly.
Indeed, the discovery of codes is an exceptionally strong argument in a dispute with actively
advancing Linux clones. Moreover, the announced transition to Linux series
government agencies in Europe is not supported by economic calculations.
Of course, Linux can be customized exactly to the needs of a specific user,
limiting the functionality of the system, but the need for such an approach is still low,
despite the fact that it requires highly qualified specialists servicing the system. IN
case with Windows opening codes will reassure those who are convinced that in the operating room
any additional spy functions are built into the system, as well as
will strengthen Microsoft's position in the market. In addition, theoretically there appears
the opportunity is exactly the same fine tuning operating system to suit your needs
specific user group.

Even officials loyal to Microsoft understand that closed source codes and
technical information makes the corporation's programs potentially dangerous for
national interests of the country. Who can guarantee that those holes that are all
hackers find time, not left by Microsoft specifically to look into
user computers? Let it not be so. Microsoft management consists of
crystal honest people. But who can guarantee that under government pressure
structures of the United States, accidental errors will not be used without
knowledge of other states on their territory? Don't forget what's coming
large-scale anti-terrorism campaign, and Microsoft is accused by many
American states and government organizations in monopolism and
unfair competition. Bill Gates is unlikely to be in this position
consistently defend the rights of citizens of other countries.

Source codes are allowed to be viewed, but can only be changed together with
Microsoft specialists. In addition, the company provides technical
information about the Windows platform to create more secure computing
systems Yes, you won’t immediately understand where the protection is, when all the intimate protective
Are operations performed with the participation and supervision of Microsoft employees? Carried
Microsoft, of course, is not in codes, but in knowledge of psychology.

Hunt for the code

A few years ago, a story involving the theft and distribution of
via Internet source code 2000 and NT 4.0. Part of the code that appeared on the Internet
was, according to experts, the first service pack for Windows 2000 and
dated July 25, 2000. It was assumed that the source of the leak was a file
unloading random access memory, generated by one of the company's computers
Mainsoft, running on Linux. During the investigation of source code leaks
operating rooms Windows systems 2000 and Windows NT it became known that in free
Access turned out to be about 15 percent of the original text of the programs. It's about
about 30,915 Windows 2000 source code files containing 13.5 million lines
text, and 95,103 files and 28 million lines of Windows NT code. The source code was
written in assembly, C and C++ programming languages.

The publication of the source code delighted the Internet community, but
alerted experts. “It’s not that the source code will fall into random hands.
nothing good,” said the senior manager of the emergency response center
antivirus company Symantec Oliver Friedrichs.- It will be able to study
attackers, and security experts will not be able to find vulnerabilities
in advance".

However, Microsoft denied and denies the possibility of any security problems.
The company said in a statement that its main concern was the possibility of theft.
the results of her work, not the security threat posed by the leak. "If
a small piece of Windows source code becomes publicly available, then this
the problem of protecting intellectual property rights, not security,” said
representative of the company. As you can see, the Company is primarily concerned with issues
financial losses. However, this is not surprising: many experts are sure that
concerns that leaked codes are leading to mass exposure
vulnerabilities are unfounded. Theoretically, for a good analytical engineer, all
the code is open source. In addition, even a brilliant hacker needs to learn code
it will take so long that by the time it is ready to use
vulnerability, an updated version of the software product will be released. Controversial
guess, right? But if it doesn’t calm you down, try alternative ones.
software products based on open source and enjoy life.

Quality on conscience of the buyer

But what about the opening of Windows 2003 code, the attentive will ask?
reader. Well, screw it, answer representatives of the IT sector. Microsoft is no one
asked to open the codes of this system. This is generally only needed by Microsoft itself.
You can clone code without Microsoft, but to get clear documentation -
No. Microsoft is looking to license its own software to have even more
access control capabilities. Back in 2004, the decision of the European Commission spoke about
that the Company must provide accurate documentation within 120 days
interface. The information disclosed had to be updated each time
release of new versions. There was no talk about source codes at all. Representatives
Microsoft smartly stated that “the source code is the final
documentation, system DNA.” Really, you can't get away with it. From such definitions in
It's time for lawyers to go crazy and start endless trials. On what,
in fact, the Company has been under construction for so many years now.

In 2004, Microsoft, by decision of the EU, provided 12,000 pages (yep, that's
not a typo – 12 thousand pages) a treatise describing the source code. Then
European experts were unable to figure it out. This year, Microsoft's
took pity and promised only 500 hours of technical support with an attempt to explain why
they wrote 12,000 pages there. It seems that Microsoft
How can, within the framework of available legislation, slow down the process known by
axiom “everything secret sooner or later becomes clear” and at the same time still trying
pursue a policy of patented products that is beneficial to itself. Program for
Microsoft's "exposure" of Windows involves providing reference information only
source code licenses. Therefore, Microsoft will allow you to view the code
detect errors in it, but will not allow you to make changes. So if you
create native applications for Windows, you can debug the code of these
applications and Windows code with associated APIs. In theory, this means that when
no one will analyze the protection functions full check Windows protection,
but it will be possible to check the components associated with your application. If
If you find an error in Windows, you will be required to report it to the office
Microsoft. And even if you suggest a way to resolve the error, the Company
reserves the right to choose whether or not to include it in the next service pack.

Even with the optimal code research option, the Company will provide approx.
95% Windows. Another three percent of the code does not seem to belong to Microsoft, but
some places - such as the product activation code - have too much
value to discover them. In addition, the spread of some
cryptographic elements are limited by the US government and cannot be
exported to other countries.

It's time to understand that Windows source codes are a myth. According to information
Microsoft, Windows OS contains several tens (if not hundreds) of millions
lines of code, which is constantly being refined and modernized. Even in the most
Companies are not entirely clear about what they have developed. Understand the code
very, very difficult. The hype that is raised from time to time around the source codes,
beneficial primarily to Microsoft itself. If the codes are not revealed, they will be saved.
trade secrets and will hide numerous errors. If they open it, it’s even better.
They will provide tighter control over licenses, hit Linux and practically
they won't lose anything. The release of a new Windows operating system is promised in 2006
Vista, the source code of which no one is going to open. I would like to ask
Microsoft – what specific benefits will the user receive from the EU Commission's decision?
What exactly will we get from the Company’s decisions on its own source code?






rem program_1
cls
@echo off
color 0A
set string=Hello World!!!
echo %string%







program_1.cmd

rem program_2
cls
@echo off
color 0A
set a=1
set timer=10
) else (echo a!=1)


Well, at least it’s understandable for many.


rem program_3
cls
@echo off
color 0A



(for /f "tokens=1-5" %A in (users.txt) do @echo %D) > emails.txt

For example, our base is “ideal”, like:

alexeykursk alexeykursk

2008-11-14T21:33:19Z 2008-11-14T21:33:19Z

Programming in Cmd introduction for beginners

-

Programming in Cmd (introduction for beginners)

This is just an introduction to cmd commands, don’t judge strictly, the article was written for Novikov, I think it will be useful for many others =)
Probably many people don’t even suspect that cmd is a universal shell,
which allows you not only to administer the system, but also to program!
Of course, the level of the language is not as high as, for example, with, but still...

To begin with, let's write a small program that will output a line written to a variable.
We go to the C:\ drive and create something like program_1.cmd there (*.bat is possible)
open it with notepad and enter the following lines there:

rem program_1
cls
@echo off
color 0A
set string=Hello World!!!
echo %string%

rem - used to describe comments
cls - if anyone else doesn’t know, this is screen clearing
@echo off - turn off the display of commands on the screen. Pay attention to @
before ECHO! It prevents commands from being echoed on a separate line.
color 0A - set the background and text color
set string=Hello World!!! - set is used to describe variables
echo %string% - displays a variable, pay attention to %%, this
denotes that it is indeed a variable and not a string!

We've sorted out the code, now let's look at the outcome of the program! We launch it for execution via cmd:
program_1.cmd
The execution result will be, you guessed it, Hellow World!!! Bright green letters on a black background

Now let’s complicate the problem a little, add a condition to this code!

rem program_2
cls
@echo off
color 0A
set a=1
set timer=10
if %a%==1 (shutdown /r -t %timer% -c "You got screwed"
) else (echo a!=1)

I think you've already guessed what the output will be. We compare the value written to the variable “a” with 1, if the condition is true, then the computer will reboot in 10 seconds, otherwise the output will read that a!=1. The example is banal and simple,
Well, at least it’s understandable for many.

Now let's move on to cycles. Let's look at the most basic example:
rem program_3
cls
@echo off
color 0A
for /l %B in (0,1,10) do echo %B

This program will display numbers in a column, from 0 to 10 in increments of 1 =) everything is as simple as...
And now a little more complicated, for can be used for more significant purposes,
for example, to enumerate files, for example you can write in cmd:

for %B in (C:*.cmd) do (echo %B)

In return you will receive all your programs with the extension *.cmd

You can also use a for loop to iterate through directories, for example

for /d %B in (C:*) do echo %B

Will show all directories on the C:\ drive (Please note, only directories, not subdirectories!)

Now let’s write an essential program that will select emails from the database and write them to another file.

(for /f "tokens=1-5" %A in (users.txt) do @echo %D) > emails.txt

For example, our base is “ideal”, sort of.

The command shell is separate software, which provides direct communication between the user and the operating system. A text-based command line user interface provides an environment in which applications and utilities with a text interface. In the command shell, programs are executed and the execution result is displayed on the screen in a form similar to the Command.com MS-DOS interpreter.

Using multiple commands and conditional symbols

You can execute multiple commands from a single command line or script using conditional processing symbols. When using multiple commands containing conditional processing symbols, the commands to the right of the conditional processing symbol will be executed depending on the results of the command to the left of the symbol. For example, you want a command to be executed only if the previous command did not execute successfully. Or it requires the command to be executed only if the previous command was executed successfully.

You can use the special characters listed in the following table to send multiple commands.

SymbolSyntaxDefinition
& [...] team1 & team2 Used to separate multiple commands on one command line. In Cmd.exe, the first command is executed, then the second command.
&& [...] team1 && team2 && , only if the command preceding this character was executed successfully. The first command is executed in Cmd.exe. The second command is executed only if the first one was executed successfully.
|| [...] team1 || team2 Runs the command behind the symbol || , only if the command preceding the symbol || was not fulfilled. The first command is executed in Cmd.exe. The second command is executed only if the first one was not executed (the resulting error code is greater than zero).
() [...] (team1 & team2) Used to group or nest commands.
; or , team1 parameter1; parameter2 Used to separate command parameters.

Notes

  • The ampersand (&), pipe (|), and parentheses () are special characters that must be preceded by a control character (^) or quotation marks if these characters are passed as arguments.
  • If the command completes the operation successfully, an error code of zero (0) or no error code is returned.

Nested shells

It is possible to nest command shells within Cmd.exe, opening a new instance of Cmd.exe from the command line. By default, each instance of Cmd.exe inherits the environment of its parent Cmd.exe application. Nesting Cmd.exe instances allows you to make changes to your local environment without affecting the parent Cmd.exe application. This allows you to retain your original Cmd.exe environment and return to it after you delete the nested command shell. Changes made to a nested shell are not saved.

To create a nested command shell, at the command prompt, enter:

A message similar to this appears:

Microsoft (R) Windows XP (TM)
(C) Copyright 1985-2001 Microsoft Corp.

To close all nested shells, enter the command exit.

You can also localize changes to the Cmd.exe instance (or script) using the commands setlocal And endlocal. Team setlocal creates a local area, and endlocal deletes it. Any changes made within the area created by the commands setlocal And endlocal, are not taken into account; thus the original environment remains unchanged. You can create up to 32 nested areas using these commands.

Using environment variables in Cmd.exe

The shell environment of Cmd.exe is defined by variables that control the behavior of the shell and operating system. You can 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. Local environment variables control the behavior of the environment in a given instance of Cmd.exe.

System environment variables are predefined in the operating system and are available to everyone Windows processes XP. Only users with administrative privileges can change these variables. These variables are most commonly used in login scripts.

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

The following list contains Various types variables in descending order of priority.

  1. Built-in system variables
  2. Hive system variables HKEY_LOCAL_MACHINE
  3. Hive Local Variables HKEY_CURRENT_USER
  4. All environment variables and paths are specified in the Autoexec.bat file.
  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. Therefore, you can change variables in the new Cmd.exe environment without affecting the parent application environment.

The following table provides a list of system and local variables.

VariableTypeDescription
%ALLUSERSPROFILE%LocalReturns the placement of the "All Users" profile.
%APPDATA%LocalReturns the default location for application data.
%CD%LocalReturns the path to the current folder.
%CMDCMDLINE%LocalReturns the command string that was used to launch this instance of Cmd.exe.
%CMDEXTVERSION%SystemReturns the version number of the current command processor extensions.
%COMPUTERNAME%SystemReturns the computer name.
%COMSPEC%SystemReturns the path to the command shell being executed.
%DATE%SystemReturns the current data. Uses the same format as the command date/t
%ERRORLEVEL%SystemReturns the error code of the last command used. A value other than zero usually indicates an error.
%HOMEDRIVE%SystemReturns the name of the local workstation drive 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 snap-in " Local users and groups."
%HOMEPATH%SystemReturns 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%SystemReturns 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.
%LOGONSEVER%LocalReturns the name of the domain controller that authenticated the current session.
%NUMBER_OF_PROCESSORS%SystemSpecifies the number of processors installed on the computer.
%OS%SystemReturns the operating system name. When using Windows 2000, the operating system name appears as Windows_NT.
%PATH%SystemSpecifies the search path for executable files.
%PATHEXT%SystemReturns a list of file extensions that are considered executable by the operating system.
%PROCESSOR_ARCHITECTURE%SystemReturns the processor architecture. Values: x86, IA64.
%PROCESSOR_IDENTFIER%SystemReturns a description of the processor.
%PROCESSOR_LEVEL%SystemReturns the model number of the processor installed on the computer.
%PROCESSOR_REVISION%SystemReturns the processor revision number.
%PROMPT%LocalReturns command line options for the current interpreter. Created by the Cmd.exe command.
%RANDOM%SystemReturns an arbitrary decimal number from 0 to 32767. Created by the Cmd.exe command.
%SYSTEMDRIVE%SystemReturns the name of the drive containing the Windows root directory (that is, the system directory).
%SYSTEMROOT%SystemReturns the location of the Windows XP system directory.
%TEMP% and %TMP%System and user
Vatelskaya
Returns the default temporary folders used by applications that are accessible to logged-in users. Some applications require the TEMP variable, others require the TMP variable.
%TIME%SystemReturns the current time. Uses the same format as the command time/t. Created by the Cmd.exe command.
%USERDOMAIN%LocalReturns the name of the domain containing the list of user accounts.
%USERNAME%LocalReturns the name of the logged in user.
%USERPROFILE%LocalReturns the profile placement for the current user.
%WINDIR%SystemReturns the location of the operating system directory.

Setting Environment Variables

Use the command set to create, delete, or display environment variables. Team set changes variables only in the environment of the current shell.

To display the variable, at the command prompt, enter:

set variable_name

To add a variable, at the command prompt, enter:

set variablename=meaning

To remove a variable, at the command prompt, enter:

set variable_name=

It is possible to use most characters as variable values, including space. When using special characters such as<, >, &, or ^ must be preceded by an escape character (^) or quotation marks. When you use quotes, they are included in the value of the variable, since all characters following the equal sign are taken as the value of the variable. Consider the following examples.

  • new&name,enter:

    set varname=new^&name

  • To create a variable value "new&name",enter:

    set varname="new&name"

  • When entered on the command line set varname=new&name The following error message appears: ""name" is not recognized as an internal or external command, operable program or batch file."

Variable names are not case sensitive. However, the team set displays the value of the variable as it was entered. You can combine the characters of the lower and uppercase in variable names to make the code easier to read (for example, UserName).

Notes

  • The maximum size of an individual environment variable is 8192 bytes.
  • The maximum total size of all environment variables, including variable names and the equal sign, is 65,536 KB.

Substituting values ​​into environment variables

To be able to substitute values ​​into an environment variable from the command line or from scripts, you must enclose the variable name in percent symbols ( % variable_name% ). The percent symbols indicate that Cmd.exe should access the values ​​of the variables rather than do a character-by-character comparison. After defining a value for a variable name, enclose the variable name in percent symbols. Cmd.exe searches for all occurrences of the variable name and replaces it with specific value variable. For example, you want to create a script that contains various values ​​(for example, usernames), and you want to define the appropriate value for the USERNAME environment variable for each user. To do this, write a script using the USERNAME variable, enclosed in quotes. When you run the script, Cmd.exe will replace occurrences of %USERNAME% with the appropriate values, eliminating the need to do this manually for each user. Value substitution is not recursive. Cmd.exe checks variables once. additional information about substituting values ​​into variables, see sections

Windows kernel:

  • USER(16, 32).dll– mouse keyboard input functions, interface input, etc. (application interaction with users and the Windows environment).
  • KERNEL(16, 32).dll– operating system functions (memory, system resource allocation, boot).
  • GDI(16, 32).dllGUI(functions for creating and displaying graphic objects).

GUI (Graphics User Interface)– standard graphical user interface. This is the part of Windows that provides support for hardware-independent graphics.

API (Application Program Interface)- interface application programs(a set of functions concentrated in Windows kernel and additional libraries).

DLL (Dynamic Link Libraries)- library dynamic linking. API functions are contained in dynamic loading libraries.

DDE– dynamic data exchange.

Windows notation ("Hungarian Charles Simonyi notation")

When programming under Windows, it is customary to use prefixes before variable names to indicate their data type. It is recommended to name your own variables and identifiers, adhering to the following principles:

  1. mnemonic meaning– the identifier should be easy to remember;
  2. semantic meaning– the role of the identifier should be clear from its name;
  3. continuity– similar objects must have similar identifiers;
  4. speed of decision making– coming up with, entering and editing an identifier should not take much time.

Some prefixes of Hungarian notation:

Prefix Meaning
A array
B boolean type (int)
By unsigned character type (byte)
C character type (1 byte)
Cb byte counter
Cr color
cx,cy short type
Dbl double (floating point)
Dw unsigned long integer (dword)
Flt float (floating point real)
Fn function
g_ prefix for global variable (global variable)
H handle (unsigned integer)
hDC handle (pointer to device context)
I integer
ID integral identifier value
L long type
Lp long pointer
Lpsz far pointer to a null-terminated string
m_ class variable
N short or int
Np near pointer
P pointer
Pfn function pointer
Pst pointer to structure
Psz pointer to a null-terminated string
Pv pointer to type void
S line
Sz null-terminated string
U unsigned character
Tm text metric
V type void
W unsigned integer (word, 16-bit)
x, y short integer (x or y coordinate)

Commonly used Windows data types:

Data type Description
HANDLE defines an identifier; A 32-bit integer used as a descriptor—a number that identifies some resource
HWND defines the window ID
HDC defines the device context identifier
LONG 32-bit signed integer
LPSTR defines a linear indicator
NULL 0
UINT Win32 data type (32 bits for Win32)
WCHAR 16-bit UNICODE character. Used to represent symbols of the world's languages

Let's add the following code:

#include LONG WINAPI WndProc(HWND, UINT, WPARAM, LPARAM); int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) ( HWND hwnd; MSG msg; WNDCLASS w; memset(&w,0,sizeof(WNDCLASS)); w.style = CS_HREDRAW | CS_VREDRAW; w.lpfnWndProc = WndProc; w.hInstance = hInstance; w.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); w.lpszClassName = "My Class"; RegisterClass(&w); hwnd = CreateWindow("My Class", "User Window", WS_OVERLAPPEDWINDOW,500, 300, 500, 380, NULL, NULL, hInstance, NULL); ShowWindow(hwnd,nCmdShow); UpdateWindow(hwnd); while(GetMessage(&msg,NULL,0,0)) ( TranslateMessage(&msg); DispatchMessage(&msg); ) return msg.wParam; ) LONG WINAPI WndProc(HWND hwnd, UINT Message, WPARAM wparam, LPARAM lparam) ( switch (Message) ( case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, Message, wparam, lparam); ) return 0 ; )

Let's compile and run the program. A Windows window will appear on the screen.