zoukankan      html  css  js  c++  java
  • windows命令行及批处理文件小结

    1、命令Shell概述(Command shell overview):

    The command shell is a separate software program that provides direct communication between the user and the operating system. The non-graphical command shell user interface provides the environment in which you run character-based applications and utilities. The command shell executes programs and displays their output on the screen by using individual characters similar to the MS-DOS command interpreter Command.com. The Windows XP command shell uses the command interpreter Cmd.exe, which loads applications and directs the flow of information between applications, to translate user input into a form that the operating system understands.

    You can use the command shell to create and edit batch files (also called scripts) to automate routine tasks. For example, you can use scripts to automate the management of user accounts or nightly backups. You can also use the Windows Script Host, CScript.exe, to run more sophisticated scripts in the command shell. You can perform operations more efficiently by using batch files than you can by using the user interface. Batch files accept all commands that are available at the command line. For more information about batch files and scripting, see Using batch files

    You can customize the command prompt window for easier viewing and to increase control over how you run programs. For more information about customizing the command prompt window, see To configure the command prompt

    1.1、Using command syntax:

    Syntax appears in the order in which you must type a command and any parameters that follow it. The following example of the xcopy command illustrates a variety of syntax text formats:

    xcopy Source [Destination] [/w] [/p] [/c] [/v] [/q] [/f] [/l] [/g] [/d[:mm-dd-yyyy]] [/u] [/i] [/s [/e]] [/t] [/k] [/r] [/h] [{/a|/m}] [/n] [/o] [/x] [/exclude:file1[+[file2]][+[file3]] [{/y|/-y}] [/z]

    The following table explains how to interpret the different text formats.

    Formatting legend

    Format Meaning

    Italic

    Information that the user must supply

    Bold

    Elements that the user must type exactly as shown

    Ellipsis (...)

    Parameter that can be repeated several times in a command line

    Between brackets ([])

    Optional items

    Between braces ({}); choices separated by pipe (|). Example: {even|odd}

    Set of choices from which the user must choose only one

    Courier font

    Code or program output

    1.2、Using multiple commands and conditional processing symbols

    You can run multiple commands from a single command line or script using conditional processing symbols. When you run multiple commands with conditional processing symbols, the commands to the right of the conditional processing symbol act based upon the results of the command to the left of the conditional processing symbol. For example, you might want to run a command only if the previous command fails. Or, you might want to run a command only if the previous command is successful.

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

    Character Syntax Definition

    & [...]

    command1 & command2

    Use to separate multiple commands on one command line. Cmd.exe runs the first command, and then the second command.

    && [...]

    command1 && command2

    Use to run the command following && only if the command preceding the symbol is successful. Cmd.exe runs the first command, and then runs the second command only if the first command completed successfully.

    || [...]

    command1 || command2

    Use to run the command following || only if the command preceding || fails. Cmd.exe runs the first command, and then runs the second command only if the first command did not complete successfully (receives an error code greater than zero).

    ( ) [...]

    (command1 & command2) 

    Use to group or nest multiple commands.

    ; or ,

    command1 parameter1;parameter2

    Use to separate command parameters.

     

    Note

    The ampersand (&), pipe (|), and parentheses ( ) are special characters that must be preceded by the escape character (^) or quotation marks when you pass them as arguments.

    If a command completes an operation successfully, it returns an exit code of zero (0) or no exit code. For more information about exit codes, see Microsoft Windows Resource Kits 

    1.3、Nesting command shells

    You can nest command shells within Cmd.exe by opening a new instance of Cmd.exe at the command prompt. By default, each instance of Cmd.exe inherits the environment of its parent Cmd.exe application. By nesting instances of Cmd.exe, you can make changes to the local environment without affecting the parent application of Cmd.exe. This allows you to preserve the original environment of Cmd.exe and return to it after you terminate the nested command shell. The changes you make in the nested command shell are not saved.

    To nest a command shell, at the command prompt, type:

    cmd

    A message similar to the following appears:

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

    To close the nested command shell, type exit.

    You can localize changes even further in an instance of Cmd.exe (or in a script) by using the setlocal and endlocal commands. Setlocal creates a local scope and endlocal terminates the local scope. Any changes made within the setlocal and endlocal scope are discarded, thereby leaving the original environment unchanged. You can nest these two commands to a maximum of 32 levels. For more information about the setlocal and endlocal commands, see Setlocal and Endlocal

    1.4、Using environment variables with Cmd.exe

    The Cmd.exe command-shell environment is defined by variables that determine the behavior of the command shell and the operating system. You can define the behavior of the command-shell environment or the entire operating system environment by using two types of environment variables, system and local. System environment variables define the behavior of the global operating system environment. Local environment variables define the behavior of the environment of the current instance of Cmd.exe.

    System environment variables are preset in the operating system and available to all Windows XP processes. Only users with administrative privileges can change system variables. These variables are most commonly used in logon scripts.

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

    The following list describes the various types of variables in descending order of precedence:

    1.

    Built-in system variables

    2.

    System variables found in the HKEY_LOCAL_MACHINE hive

    3.

    Local variables found in the HKEY_CURRENT_USER hive

    4.

    All environment variables and paths set in the Autoexec.bat file

    5.

    All environment variables and paths set in a logon 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 the variables in the new Cmd.exe environment without affecting the environment of the parent application.

    The following table lists the system and local environment variables for Windows XP.

    Variable Type Description

    %ALLUSERSPROFILE%

    Local

    Returns the location of the All Users Profile.

    %APPDATA%

    Local

    Returns the location where applications store data by default.

    %CD%

    Local

    Returns the current directory string.

    %CMDCMDLINE%

    Local

    Returns the exact command line used to start the current Cmd.exe.

    %CMDEXTVERSION%

    System

    Returns the version number of the current Command Processor Extensions.

    %COMPUTERNAME% 

    System

    Returns the name of the computer.

    %COMSPEC% 

    System

    Returns the exact path to the command shell executable.

    %DATE% 

    System

    Returns the current date. Uses the same format as the date /t command. Generated by Cmd.exe. For more information about the date command, see Date

    %ERRORLEVEL% 

    System

    Returns the error code of the most recently used command. A non zero value usually indicates an error.

    %HOMEDRIVE% 

    System

    Returns which local workstation drive letter is connected to the user's home directory. Set based on the value of the home directory. The user's home directory is specified in Local Users and Groups.

    %HOMEPATH% 

    System

    Returns the full path of the user's home directory. Set based on the value of the home directory. The user's home directory is specified in Local Users and Groups.

    %HOMESHARE% 

    System

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

    %LOGONSEVER% 

    Local

    Returns the name of the domain controller that validated the current logon session.

    %NUMBER_OF_PROCESSORS% 

    System

    Specifies the number of processors installed on the computer.

    %OS% 

    System

    Returns the operating system name. Windows 2000 displays the operating system as Windows_NT.

    %PATH%

    System

    Specifies the search path for executable files.

    %PATHEXT%

    System

    Returns a list of the file extensions that the operating system considers to be executable.

    %PROCESSOR_ARCHITECTURE% 

    System

    Returns the chip architecture of the processor. Values: x86, IA64.

    %PROCESSOR_IDENTIFIER%

    System

    Returns a description of the processor.

    %PROCESSOR_LEVEL% 

    System

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

    %PROCESSOR_REVISION%

    System

    Returns the revision number of the processor.

    %PROMPT%

    Local

    Returns the command prompt settings for the current interpreter. Generated by Cmd.exe.

    %RANDOM%

    System

    Returns a random decimal number between 0 and 32767. Generated by Cmd.exe.

    %SYSTEMDRIVE%

    System

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

    %SYSTEMROOT% 

    System

    Returns the location of the Windows XP root directory.

    %TEMP% and %TMP%

    System and User

    Returns the default temporary directories that are used by applications available to users who are currently logged on. Some applications require TEMP and others require TMP.

    %TIME%

    System

    Returns the current time. Uses the same format as the time /t command. Generated by Cmd.exe. For more information about the time command, see Time

    %USERDOMAIN%

    Local

    Returns the name of the domain that contains the user's account.

    %USERNAME%

    Local

    Returns the name of the user who is currently logged on.

    %USERPROFILE%

    Local

    Returns the location of the profile for the current user.

    %WINDIR%

    System

    Returns the location of the operating system directory.

    1.5、Setting environment variables

    Use the set command to create, change, delete, or display environment variables. The set command alters variables in the current shell environment only.

    To view a variable, at a command prompt, type:

    set VariableName

    To add a variable, at a command prompt, type:

    set variablename=value

    To delete a variable, at a command prompt, type:

    set VariableName=

    You can use most characters as variable values, including white space. If you use the special characters <, >, |, &, or ^, you must precede them with the escape character (^) or quotation marks. If you use quotation marks, they are included as part of the value because everything following the equal sign is taken as the value. Consider the following examples:

    To create the variable value new&name, type:

    set varname=new^&name

    To create the variable value "new&name", type:

    set varname="new&name"

    If you type set varname=new&name at the command prompt, an error message similar to the following appears:

    "'name' is not recognized as an internal or external command, operable program or batch file."

    Variable names are not case-sensitive. However, set displays the variable exactly as you typed it. You can combine uppercase and lowercase letters in your variable names to make your code more readable (for example, UserName).

     

    Note

    The maximum individual environment variable size is 8192bytes.

    The maximum total environment variable size for all variables, which includes variable names and the equal sign, is 65,536KB.

    1.6、Substituting environment variable values

    To enable the substitution of variable values at the command line or in scripts, enclose the variable name in percent signs (that is, %variablename%). By using percent signs, you ensure that Cmd.exe references the variable values instead of making a literal comparison. After you define variable values for a variable name, enclose the variable name in percent signs. Cmd.exe searches for all instances of the variable name and replaces it with the defined variable value. For example, if you create a script that contains different values (for example, user names) and you want to define the USERNAME environment variable for each user with these values, you can write one script using the variable USERNAME enclosed in percent signs. When you run this script, Cmd.exe replaces %USERNAME% with the variable values, which eliminates the need to perform this task manually for each user. Variable substitution is not recursive. Cmd.exe checks variables once. For more information about variable substitution, see For and Call

    2、使用批处理文件:(msdn):

    3、具体命令:

    3.1、echo与@

    echo可以说是批处理文件中最简单的指令了。我们知道批处理文件是按行执行的,也就是每一行执行一次,命令提示符也相应地一行出现一次,我跟我们自己手动输入一行命令一样。但我们通常希望批处理文件中的命令执行即可,而不用显示命令自身,这时echo就派上用场了。

    3.1.1 echo命令语法如下:

    echo [{on|off}] [message]

    3.1.2 参数使用:

    • (1)on/off:关闭或开启命令自身的显示功能
    • (2)message :显示一条消息
    • (3)/?:显示echo命令的帮助信息
    • (4)echo命令还可以与重定向符一起使用,譬如把一条命令语句导入到一个文件之中
    [注]:命令行好像不支持命令嵌套 echo set name = "victor-ma",这只是一个显示命令,不会被识别为set指令。
    [注]:前面说到,echo可以与重定向符一起配合使用,且echo可以出现在管道命令中,所以要显示<> |就需要一些特殊的手段。方法是在这些符号前加^,譬如^< ^|,那么要显示^就是^^了。
     

    3.1.3 @

    想屏蔽当前命令行本身的显示,只要在命令前加@符号即可。譬如我们连echo off也不想让它显示出来,那就使用@echo off语句即可。@不应该被视为一个命令。

    4、符号:

    4.1、使用重定向操作符:

    4.1.1、重定向操作符:

    • >    将命令输出写入到文件或设备(例如打印机)中,而不是写在命令提示符窗口中。
    • <    从文件中而不是从键盘中读入命令输入
    • >>  将命令输出添加到文件末尾而不删除文件中的信息
    • >&  将一个句柄的输出写入到另一个句柄的输入中
    • <&  从一个句柄读取输入并将其写入到另一个句柄输出中
    • |     从一个命令中读取输出并将其写入另一个命令的输入中。也称为管道

    默认情况下,cmd.exe从键盘接受命令输入,键盘以STDIN handle(标准输入)表示;向命令提示符窗口发送命令输出,命令提示符窗口以STDOUT handle(标准输出)表示。

    4.1.2、重定向涉及的句柄:

    上面已经提到了STDIN和STDOUT两个句柄了,我们再来总的看一下重定位中涉及到的所有句柄:

    • 句柄           句柄值   句柄描述
    • STDIN        0          键盘输入
    • STDOUT     1          命令提示符窗口输出
    • STDERR      2         命令提示符窗口错误输出
    • UNDEFINED 3-9      这些句柄的意义由各应用程序自由定义。

    【注】其实还有一个句柄,称为nul

    4.1.3、一些必须强调的问题:

    命令行中的一条指令就是一个应用程序。重定向的主体是指令的输入、输出和错误输出。重定向只对当前指令有效。

    4.1.4、实例:

    从定向比较难理解,需要多一些实例来帮助理解其应用。

    4.1.4.1、复制句柄:
    4.1.4.2、重定向命令的输入(<):

    <使命令的输入从键盘转向文件或设备。譬如要把test.txt中的内容以行为单位按字符顺序排序并把结果输出在命令行窗口中,我们可以:

    sort<test.txt

    这条命令把sort指令的输入从标准输入重定向为test.txt。

    4.1.4.3、重定向命令的输出(>):

    几乎所有的命令都会把输出送到命令提示窗口中去。甚至那些把输出送到驱动器或者打印机的命令也会在命令提示窗口中显示消息。

    用>可以把命令的输出从标准输出重定位到文件或设备中去。大部分的指令都可以使用这个操作符。譬如dir指令:

    dir>dirlist.txt

    如果dirlist.txt不存在,Cmd.exe创建它。如果dirlist.txt文件已经存在,Cmd.exe替换文件内容为dir命令的输出。

    To redirect command output from the Command Prompt window to a file or device, use the > operator. You can use this operator with most commands. For example, to redirect dir output to Dirlist.txt:

    dir>dirlist.txt

    If Dirlist.txt does not exist, Cmd.exe creates it. If Dirlist.txt exists, Cmd.exe replaces the information in the file with the output from the dir command.

    To run the netsh routing dump command and then send the command output to Route.cfg, type:

    netsh routing dump>c: oute.cfg

    The > operator opens the specified file with write-only access. As a result, you cannot read the file when you use this operator. For example, if you start a program with redirection >&0, all attempts to write handle 1 fail because handle 0 is initially opened with read-only access.

    4.1.4.4、重定向输入和复制(<&):

    Using the <& operator to redirect input and duplicate

    To use the redirection input operator <&, the file you specify must already exist. If the input file exists, Cmd.exe opens it as read-only and sends the characters contained in the file as input to the command as if they were input from the keyboard. If you specify a handle, Cmd.exe duplicates the handle you specify onto the existing handle in the system.

    For example, to open File.txt as input read to handle 0 (that is, STDIN), type:

    < file.txt

    To open File.txt, sort the contents and then send the output to the Command Prompt window (that is, STDOUT), type:

    sort< file.txt 

    To find File.txt, and then redirect handle 1 (that is, STDOUT) and handle 2 (that is, STDERR) to the Search.txt, type:

    findfile file.txt>search.txt 2<&1

    To duplicate a user-defined handle 3 as input read to handle 0 (that is, STDIN), type:

    <&3

    4.2、转义符号:

    当命令行中出现一个插入符(^)时,紧跟其后的字符按字面意义解释而不是按控制字符解释。譬如第一章节提到的,当需要把与字符、管道字符、圆括号等字符作为参数传递时须用转义字符或用引号括起。

     

    2、findstr - 在文件中查找字符串

    这个命令的使用通过帮助(findstr /?)一目了然,但/s(在当前目录和所有子目录中搜索匹配文件)使用有些不直观。直接使用/s选项命令会卡死,只能使用ctrl+c结束,必须使用形如/s *.txt(目录和子目录下的txt文件)、/s *(目录和自目录下所有文件)的格式才能正常工作。

  • 相关阅读:
    AC自动机模板
    HDU 3065 病毒侵袭持续中(AC自动机)
    HDU 2896 病毒侵袭(AC自动机)
    HDU 2222 Keywords Search (AC自动机模板题)
    HDU 1113 Word Amalgamation
    HDU 1171 Big Event in HDU(母函数或01背包)
    37.Qt网络与通信
    2.Matlab数值数组及其运算
    36.QT地图
    35.QT蝴蝶飞舞
  • 原文地址:https://www.cnblogs.com/victor-ma/p/3899508.html
Copyright © 2011-2022 走看看