An article takes you through batch commands

Posted by joliocesar on Sat, 12 Feb 2022 01:24:09 +0100

Batch processing, as its name implies, can simplify complex things. It first appeared in dos operating system, that is, cmd black window, which was used most in the early days when there was no gui interface, and the commands were relatively rich. Although many functions are encapsulated in software now, But you will find that it will be faster to perform operations in dos, even if it will be more troublesome, if you can't stand the slow pace.

Let's take a look at the basic commands below. First, open the cmd window:

You can use the shortcut key logo key + R and enter cmd, or click the lower right corner of the window system, click Run and enter cmd.

Let's take a look:

After opening, you can see this picture. We can do some operations on him to make him look cool.

Let's first look at how to operate and open the properties dialog box:

Finally, we got such a window. Is it a little cooler than the previous one? Ha ha.

So what are the commands in dos? Let's take a look:

In this way, some dos operating system commands are obtained, which can also be batch processed, so we vividly call it batch script. So how are these commands used.

1, Display, pause, clear, comment

1.echo output information

2.pause

If you don't believe it, you can take a look at this:

  1. cls clear

 

After clearing, there is no display. Clearing means clearing all the contents in front.

4.rem notes

In addition:: can also play the role of rem annotation, which is more concise and effective.

2, File directory operation

1. cd switching directory

2. md create folder

 

3. ren rename

4. move folder

 

5. del delete file

6. copy # xcopy copy files

Many people think the two methods are the same, but they are actually different. When you copy super large files, I think everyone will basically encounter the embarrassment of slow copying. If you make good use of dos commands, you can improve your efficiency by at least ten times. Copy itself is faster than system replication, but xcopy is faster.

7.dir enumerate file names

You can print out the names of all files (folders) in the current directory

8. File attributes

3, Network command

1.net # display and set network user group account

The syntax of this command is:
NET    [ ACCOUNTS | COMPUTER | CONFIG | CONTINUE | FILE | GROUP | HELP |      HELPMSG | LOCALGROUP | PAUSE | SESSION | SHARE | START |      STATISTICS | STOP | TIME | USE | USER | VIEW ]

2.netstat displays protocol statistics and current TCP/IP network connection

NETSTAT [-a] [-b] [-e] [-f] [-n] [-o] [-p proto] [-r] [-s] [-t] [interval]
  -a            Displays all connection and listening ports.  -b            Displays the executable programs involved in creating each connection or listening port.                In some cases, it is known that an executable carries multiple independent programs                Component that, in these cases, shows the time involved in creating a connection or listening port                And the sequence of components. In this case, the name of the executable program                At the bottom[]In, the component it calls is at the top until it reaches                reach TCP/IP. Note that this option can be time-consuming and can be used when you don't have one                May fail when sufficient permissions are available.  -e            Displays Ethernet statistics. This option can be used with -s Option.  -f            Displays the fully qualified domain name of the external address(FQDN).   -n            Displays the address and port number in numeric form.  -o            Displays the processes that are owned and associated with each connection ID.   -p proto      display proto Connection of the specified protocol; proto Can be any of the following                He Yi: TCP,UDP,TCPv6 or UDPv6. If with -s choose                Items are used together to display statistics for each protocol, proto Can be any of the following                He Yi: IP,IPv6,ICMP,ICMPv6,TCP,TCPv6,UDP                or UDPv6.   -r            Displays the routing table.  -s            Displays statistics for each protocol. By default, the                IP,IPv6,ICMP,ICMPv6,TCP,TCPv6,UDP and UDPv6                Statistics of;-p Option allows you to specify the default subnet.  -t            Displays the current connection uninstall status.  interval      Redisplay the selected statistics, the number of seconds between each display pause.                Press CTRL+C Stop redisplaying statistics. If omitted, then netstat                The current configuration information will be printed once.

3.ping} test IP connection

usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]           [-r count] [-s count] [[-j host-list] | [-k host-list]]           [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name
 option:    -t             Ping Specify the host until it stops.                   To view statistics and continue - Please type Control-Break;                   To stop - Please type Control-C.     -a             Resolve the address to the host name.    -n count       The number of echo requests to send.    -l size        Send buffer size.    -f             Set the "no segmentation" flag in the packet(Only for IPv4).     -i TTL         Survival time.    -v TOS         Service type(Only for IPv4. This setting is deprecated and                   yes IP The service field type in the header has no effect).     -r count       Record the route of counting hops(Only for IPv4).     -s count       Timestamp of count hops(Only for IPv4).     -j host-list   Loose source routing with host list(Only for IPv4).     -k host-list   Strict source routing with host list(Only for IPv4).     -w timeout     Timeout for waiting for each reply(millisecond).     -R             Also use the route header to test the reverse route(Only for IPv6).     -S srcaddr     The source address to use.    -4             Mandatory use IPv4.     -6             Mandatory use IPv6. 

4.ipconfig view local network configuration

usage:    ipconfig [/allcompartments] [/? | /all |                                 /renew [adapter] | /release [adapter] |                                 /renew6 [adapter] | /release6 [adapter] |                                 /flushdns | /displaydns | /registerdns |                                 /showclassid adapter |                                 /setclassid adapter [classid] |                                 /showclassid6 adapter |                                 /setclassid6 adapter [classid] ]
among    adapter             Connection name                       (Wildcards are allowed * and ?,See Example)
    option:       /?               Show this help message       /all             Displays complete configuration information.       /release         Releases the of the specified adapter IPv4 Address.       /release6        Releases the of the specified adapter IPv6 Address.       /renew           Updates the of the specified adapter IPv4 Address.       /renew6          Updates the of the specified adapter IPv6 Address.       /flushdns        eliminate DNS Resolver cache.       /registerdns     Refresh all DHCP Lease and re register DNS name       /displaydns      display DNS Parses the contents of the program cache.       /showclassid     Displays all allowed for the adapter DHCP class ID.        /setclassid      modify DHCP class ID.        /showclassid6    Displays all allowed by the adapter IPv6 DHCP class ID.        /setclassid6     modify IPv6 DHCP class ID. 

By default, only those bound to are displayed TCP/IP Of adapter IP Address, subnet mask, and default gateway.
about Release and Renew,If no adapter name is specified, all bindings to the adapter are released or updated TCP/IP Of adapter IP Address lease.
about Setclassid and Setclassid6,If not specified ClassId,Will be deleted ClassId. 
Examples:    > ipconfig                       ... display information    > ipconfig /all                  ... Show details    > ipconfig /renew                ... Update all adapters    > ipconfig /renew EL*            ... Update all names to EL start                                         Connection of    > ipconfig /release *Con*        ... Release all matching connections,                                         for example "Local Area Connection 1" or                                             "Local Area Connection 2"    > ipconfig /allcompartments      ... Displays information about all segments                                         information    > ipconfig /allcompartments /all ... Displays information about all segments                                         detailed information
 

5.arp address translation protocol

ARP -s inet_addr eth_addr [if_addr]ARP -d inet_addr [if_addr]ARP -a [inet_addr] [-N if_addr] [-v]
  -a            Display the current protocol by asking for the current protocol data ARP Item.                If specified inet_addr,Only the specified computers are displayed                of IP Address and physical address. If more than one network                Interface use ARP,Show each ARP Table entry.  -g            And -a Same.  -v            Displays the current in detail mode ARP Item. All invalid items                Items on the and loopback interfaces are displayed.  inet_addr     appoint Internet Address.  -N if_addr    display if_addr Of the specified network interface ARP Item.  -d            delete inet_addr Specified host. inet_addr can                So it's a wildcard *,To delete all hosts.  -s            Add host and add Internet address inet_addr                And physical address eth_addr Associated. The physical address is                Six hexadecimal bytes separated by hyphens. This item is permanent.  eth_addr      Specify the physical address.  if_addr       If it exists, this item specifies the interface that the address translation table should modify                of Internet Address. If it does not exist, the first one is used                A suitable interface. Examples:  > arp -s 157.55.85.212   00-aa-00-62-c6-09.... Add a static item.  > arp -a                                  .... display ARP Watch.
 

6.route network routing table

ROUTE [-f] [-p] [-4|-6] command [destination]                  [MASK netmask]  [gateway] [METRIC metric]  [IF interface]
  -f           Clear the routing table for all gateway entries. If with a               Command. Before running the command,               The routing table should be cleared.
  -p           And ADD When used in conjunction with the command, set the route to               Remains unchanged during system boot. By default, when you restart the system,               Do not save route. Ignore all other commands,               This will always affect the corresponding permanent route. Windows 95               This option is not supported.
  -4           Mandatory use IPv4. 
  -6           Mandatory use IPv6. 
  command      One of:                 PRINT     Print route                 ADD       Add route                 DELETE    Delete route                 CHANGE    Modify an existing route  destination  Specify the host.  MASK         Specifies that the next parameter is the netmask value.  netmask      Specifies the subnet mask value for this routing entry.               If not specified, the default setting is 255.255.255.255.   gateway      Specify the gateway.  interface    Specifies the interface number of the route.  METRIC       Specify the metric, such as the cost of the target.
All symbolic names used for the target can be in the network database file NETWORKS Find in. The symbolic names used for the gateway can be found in the host name database file HOSTS Find in.
If the command is PRINT or DELETE. The destination or gateway can be a wildcard,(Wildcards are specified as asterisks“*"),Otherwise, gateway parameters may be ignored.
If Dest Include one * or ?,Will be treated as Shell Mode, and only print matching target routes. “*"Match any string, and“?"Match any character. Examples: 157.*.1,157.*,127.*,*224*. 
Only in PRINT Pattern matching is only allowed in the command. Diagnostic information notes:    invalid MASK An error occurs when (DEST & MASK) != DEST Time.    Examples: > route ADD 157.0.0.0 MASK 155.0.0.0 157.55.80.1 IF 1             Route addition failed: The specified mask parameter is invalid.             (Destination & Mask) != Destination. 
Examples:
    > route PRINT    > route PRINT -4    > route PRINT -6    > route PRINT 157*          .... Print only those that match 157* Item
    > route ADD 157.0.0.0 MASK 255.0.0.0  157.55.80.1 METRIC 3 IF 2             destination^      ^mask      ^gateway     metric^    ^                                                         Interface^      If not given IF,It will try to find the best for a given gateway      Interface.    > route ADD 3ffe::/32 3ffe::1
    > route CHANGE 157.0.0.0 MASK 255.0.0.0 157.55.80.5 METRIC 2 IF 2
      CHANGE Only used to modify gateway and/Or metric.
    > route DELETE 157.0.0.0    > route DELETE 3ffe::/32

7.tracert route tracking

usage: tracert [-d] [-h maximum_hops] [-j host-list] [-w timeout]               [-R] [-S srcaddr] [-4] [-6] target_name
 option:    -d                 Do not resolve addresses to host names.    -h maximum_hops    The maximum metric of the search target.    -j host-list       Loose source routing with host list(Only for IPv4).     -w timeout         Timeout for waiting for each reply(In Milliseconds ).     -R                 Track round trip path(Only for IPv6).     -S srcaddr         Source address to use(Only for IPv6).     -4                 Mandatory use IPv4.     -6                 Mandatory use IPv6. 

 

4, System command

1.taskkill} killing process

TASKKILL [/S system [/U username [/P [password]]]]         { [/FI filter] [/PID processid | /IM imagename] } [/T] [/F]
describe:    Use the tool to follow the process ID (PID) Or image name to terminate the task.
parameter list:    /S    system           Specify the remote system to connect to.
    /U    [domain\]user    Specify the user context in which the command should be executed.
    /P    [password]       Specify the password for the provided user context. If omitted, prompt                           Input.
    /FI   filter           Apply a filter to select a set of tasks.                           Allow to use "*". For example, the image name eq acme*
    /PID  processid        Specifies the name of the process to terminate PID.                            use TaskList obtain PID. 
    /IM   imagename        Specifies the image name of the process to terminate. wildcard '*'Can be used                           Specify all task or image names.
    /T                     Terminates the specified process and the child processes enabled by it.
    /F                     Specifies that the process is forcibly terminated.
    /?                     Displays help messages.
Filter:    Filter name      Valid operator                Effective value    -----------   ---------------           -------------------------    STATUS        eq, ne                    RUNNING |                                            NOT RESPONDING | UNKNOWN    IMAGENAME     eq, ne                    Image Name     PID           eq, ne, gt, lt, ge, le    PID value    SESSION       eq, ne, gt, lt, ge, le    Session number.    CPUTIME       eq, ne, gt, lt, ge, le    CPU Time in the format                                            hh:mm:ss.                                             hh - When,                                            mm - Points, ss - second    MEMUSAGE      eq, ne, gt, lt, ge, le    Memory usage in KB    USERNAME      eq, ne                    User name in the format [domain\]user    MODULES       eq, ne                    DLL name    SERVICES      eq, ne                    Service name    WINDOWTITLE   eq, ne                    Window title
    explain    ----    1) Only when a filter is applied,/IM Switch to use wildcards '*'.     2) Remote processes are always forced (/F) Termination.    3) Not supported when specifying a remote machine "WINDOWTITLE" and "STATUS" Filter.
for example:    TASKKILL /IM notepad.exe    TASKKILL /PID 1230 /PID 1241 /PID 1253 /T    TASKKILL /F /IM cmd.exe /T    TASKKILL /F /FI "PID ge 1000" /FI "WINDOWTITLE ne untitle*"    TASKKILL /F /FI "USERNAME eq NT AUTHORITY\SYSTEM" /IM notepad.exe    TASKKILL /S system /U domain\username /FI "USERNAME ne NT*" /IM *    TASKKILL /S system /U username /P password /FI "IMAGENAME eq note*"
 

2.shutdown shut down or restart the computer

usage: shutdown [/i | /l | /s | /r | /g | /a | /p | /h | /e] [/f]    [/m \\computer][/t xxx][/d [p|u:]xx:yy [/c "comment"]]
    No parameters show help. This is different from typing /? It's the same.    /?         Display help. This is the same as not typing any options.    /i         Display graphical user interface(GUI).                This must be the first option.    /l         cancellation. This cannot be compared with /m or /d Option.    /s         Turn off the computer.    /r         Shut down and restart your computer.    /g         Shut down and restart your computer. After the system restarts,               Restart all registered applications.    /a         Abort system shutdown.               This can only be used during timeout.    /p         Shut down the local computer without timeout or warning.               Can be with /d and /f Use with options.    /h         Hibernate the local computer.               Can be with /f Option.    /e         Record the reason why the computer shut down unexpectedly.    /m \\computer Specify the target computer.    /t xxx     Set the timeout before shutdown to xxx Seconds.               The valid range is 0-315360000 (10 year),The default value is 30.               If the timeout is greater than 0, it is implied /f               Parameters.    /c "comment" Comment on the reason for the restart or shutdown.               A maximum of 512 characters is allowed.    /f         Force the running application to close without warning the user in the foreground.               should be /t When the parameter specifies a value greater than 0,               Implied /f Parameters.    /d [p|u:]xx:yy  Provide reasons for restarting or shutting down.               p Indicates that the restart or shutdown is planned.               u Indicates that the reason is user-defined.               If p and u If none is specified, it is an unplanned restart               Or off.               xx Is the main reason number(Positive integer less than 256).                yy Is the secondary reason number(Positive integer less than 65536). 
Reasons on this computer:(E = expect U = accident P = Within the plan, C = custom)category    main    secondary    title
 U      0       0       other(Outside the plan)E       0       0       other(Outside the plan)E P     0       0       other(inside the plan) U      0       5       Other faults: The system is not responding E       1       1       Hardware: maintain(Outside the plan)E P     1       1       Hardware: maintain(inside the plan)E       1       2       Hardware: install(Outside the plan)E P     1       2       Hardware: install(inside the plan)E       2       2       operating system: recovery(inside the plan)E P     2       2       operating system: recovery(inside the plan)  P     2       3       operating system: upgrade(inside the plan)E       2       4       operating system: Reconfigure(Outside the plan)E P     2       4       operating system: Reconfigure(inside the plan)  P     2       16      operating system: Service Pack (inside the plan)        2       17      operating system: Hot repair(Outside the plan)  P     2       17      operating system: Hot repair(inside the plan)        2       18      operating system: Safety repair(Outside the plan)  P     2       18      operating system: Safety repair(inside the plan)E       4       1       application program: maintain(Outside the plan)E P     4       1       application program: maintain(inside the plan)E P     4       2       application program: install(inside the plan)E       4       5       application program: No response E       4       6       application program: instable U      5       15      system failure : Stop error U      5       19      safety problem E       5       19      safety problem E P     5       19      safety problem E       5       20      Loss of network connection(Outside the plan) U      6       11      Power failure: The wire was pulled out U      6       12      Power failure: environment  P     7       0       Old edition API Shut down

3.start command

START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]      [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]      [/NODE <NUMA node>] [/AFFINITY <hex affinity mask>] [/WAIT] [/B]      [command/program] [parameters]
    "title"     The title displayed in the window title bar.    path        Boot directory.    B           Start the application without creating a new window. Application ignored ^C handle.                Unless the application is enabled ^C Handle, otherwise ^Break Is the only thing that can be interrupted                How the application works.    I           The new environment will be passed on to cmd.exe The original environment, not the current environment.
    MIN         Start the window in a minimized manner.    MAX         Start the window in a maximized manner.    SEPARATE    Start 16 bits in a separate memory space Windows Procedure.    SHARED      Start 16 bit in shared memory space Windows Procedure.    LOW         stay IDLE Start the application in the priority class.    NORMAL      stay NORMAL Start the application in the priority class.    HIGH        stay HIGH Start the application in the priority class.    REALTIME    stay REALTIME Start the application in the priority class.    ABOVENORMAL stay ABOVENORMAL Start the application in the priority class.    BELOWNORMAL stay BELOWNORMAL Start the application in the priority class. NODE        Non consistent memory structures will be preferred (NUMA) Node is specified as a decimal integer. AFFINITY    Specifies the processor affinity mask as a hexadecimal number. Processes are limited to these                    Run on the processor.
             When /AFFINITY and /NODE When combined, the correlation mask will be interpreted differently.             Specify the affinity mask, as shown in NUMA The processor mask of the node is correctly moved to zero             The starting position is the same. The process is restricted to the specified affinity mask and NUMA Between nodes             Run on those general-purpose processors. If there is no general-purpose processor, the process is limited to             designated NUMA Run on node. WAIT        Start the application and wait for it to terminate. command/program             If it's internal cmd Command or batch file, the command processor is using             cmd.exe of /K The switch operates. This means that after running the command, the window             Will still exist.
             If it's not internal cmd Command or batch file, then it is a program and will             Run as a windowed application or console application.
 parameters  These are passed to command/program Parameters for.
meaning: Not supported on 64 bit platforms SEPARATE and SHARED Options.
Over designation /NODE,Available according to NUMA Create processes in the way of memory areas in the system. For example, to create two processes that communicate with each other entirely through shared memory to share the same preferences NUMA Nodes while minimizing memory latency. If possible, they are assigned from the same source NUMA The memory of the node and will run freely on a processor other than the specified node.
 start-up /NODE 1 application1.exe start-up /NODE 1 application2.exe
 The two processes can be further limited to the same NUMA Runs on the specified processor within the node. In the following example, application1 Runs on two low order processors of the node, and application2 The node runs on the next two processors. This example assumes that the specified node has at least four logical managers. Note that the node number can be changed to any valid node number for this computer without changing the association code.
 start-up /NODE 1 /AFFINITY 0x3 application1.exe start-up /NODE 1 /AFFINITY 0xc application2.exe
 If command extension is enabled, through the command line or START The external command of the command will be changed as follows:
The file name is typed as a command, and non executable files can be called through file association. (For example, WORD.DOC Will call with .DOC Application associated with file extension).  For information on how to create these associations from within a command script, see ASSOC and  FTYPE Command.
The application of the line is 32-position GUI When the application, CMD.EXE Return to the command prompt before the application terminates. If executed within a command script, the new behavior does not occur.
If the first symbol of the command line executed is a string without extension or path modifier "CMD","CMD" Will be COMSPEC Replaced by the value of the variable. This prevents extraction from the current directory CMD.EXE. 
If the first symbol of the executed command line has no extension, CMD.EXE Can use PATHEXT The value of the environment variable determines which extensions to look for in what order. PATHEXT The default value of the variable is:
     .COM;.EXE;.BAT;.CMD
 Note that this syntax follows PATH Like variables, semicolons separate different elements.
When looking for an executable, if there is no matching extension, see if the name matches the directory name. If so, START Will be called on that path lorer. If executed from the command line, it is equivalent to modifying that path CD /D. 

After talking about so many basic sentences, are you eager to try? In fact, there are many advanced things in batch processing, such as loop judgment and set setting. Let's have a look.

1.if statement

As we all know, the if statement is basically used to judge, such as whether two numbers are the same and whether a variable exists. Its usage is as follows:

As you can see, this completes a very mentally retarded judgment sentence, hahaha. After knowing this simple syntax, should we have something new, such as variables

You can see that using the keyword set to define variables completes the interactive operation and assignment.

After judgment, variables, and of course loops, the for loop is no stranger to us. It can be found everywhere, and dos is no exception.

However, it seems that the operation of this for statement is different in the cmd window and in the batch file. Specifically, the former needs to add a% before the variable, while the latter needs two%%. There are three keywords in the for statement: for, in and do , all of which are indispensable.

How about it? Is it super simple. Of course, it also has many interesting places. For example, if you want to view all the files in a directory:

This will print out all txt files in the current desktop directory.

Topics: Python