新进化论

道生一,一生二,二生三,三生万物。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
There are certain little tricks that books on the command prompt don't always tell you. Or, if they do, the description is buried away in a paragraph somewhere. Experienced users of the command line know all about these. However, average users may not and I am going to mention a few useful tips for them. As far as I know the tips work inWindows XP, Vista, and Windows 7 except where noted. Tips for Vista/7 only are given on another page.

How to make a blank line in a batch file

Sometimes you would like a blank line or two in the output from a batch file. It isn't immediately clear how to do this. Simply entering "echo" doesn't work because that will output the status of command echoing. The trick is to enterecho.Note that "echo" is followed by a period with no space in between.

Force the "echo" command not to parse arguments

The preceding tip is a special case of a more general method for using the "echo" command. Although the command is used to display text or messages, it can also take certain arguments such as "on" or "off". If you writeecho offyou will not get a display of the string "off" but will actually be configuring the "echo" command itself. To display the string "off", you would useecho. offIn other words, placing a period at the end of "echo" forces the command to simply display whatever follows without checking to see if the string is one of the special cases.

Check if a file exists

A special variant of the "If" statement can be used to find out if a file is already present. The statement isif exist somefile somecommandThe statement can also test for non-existence of a file withif not exist somefile somecommand

The useful device "nul"

The invisible null device called "nul" has a number of uses. (It's also sometimes called the "bit bucket" or the "black hole".) Anything sent to it disappears. It can be used in statements when you do not want output to be dIsplayed. For example the commandsomecommand > nulwill carry out some command but send whatever is the normal output into oblivion. Sometimes in a batch file you do not want any possible error messages to be displayed. This is done by usingsomecommand 2> nul

Stopping a runaway command

Sometimes you start a command only to find that it is going on and on, spewing out screen after screen of output. Most of the time you can terminate a command by simultaneously pressing the two keys "Ctrl" and "c".

Pausing a scrolling screen

If you have a command with a lot of output,, you can pause the scrolling so that you can read what's on the screen. Use the keyboard combination "Ctrl+s". To resume scrolling, repeat Ctrl+s

Use drag and drop

Having to type the fully qualified path of a file every time it's needed in a command can be tedious and subject to error. Many people are unaware that a file can be dragged from a folder or Windows Explorer view and dropped on an open command window. It saves a lot of typing. (Doesn't work in Vista)

Go up one level above the working directory

Any Unix user knows this one but it's often new to Windows users. To go up to the directory that is one level above the working directory, entercd ..You can repeat this to go up more levels. It's a little off the subject of the command shell but in the Start-Run line just entering the two periods ".." will also take you up one level from the default working directory (the working directory is normally
%USERPROFILE%)

How to get to the C: drive

If you want to use the C: drive as the working directory, entercd ..twice. Note that either cd C: or pushd C: do not work.

General way to get to the root folder

In general, you can get to the root or drive by the commandcd \(Thanks to Michael Leonard for suggesting this tip.)

How to change the working directory to a folder on a different drive

If you want to change the working directory for a command window to a folder on a different drive, the command "cd" doesn't work. You have to first enter the drive letter and colon and then enter "cd" and the folder path. However, you can use the switch /d to change the current working directory drive as shown below:cd /d E:\testYou can also make the change with one command entry if you use "pushd" instead of "cd":pushd E:\test

Watch out for spaces in file and folder names

The command shell does not recognize spaces in path names. Any path name with spaces must be enclosed in quotation marks. This problem often crops up in scripts where certain environment variables or input arguments are used. For safety, variables that involve file or folder names should be enclosed in quotes.

Special treatment of variables in "For" statements in batch files

"For" statements are very useful, providing powerful iterative methods. They have the peculiarity, however, of requiring double percent signs for iteration variables in batch files. in other words the syntax in a batch file is:for %%variable In set Do statementIf a "For" loop is run directly from the command line, only a single percent sign is used. The syntax is then:for %variable In set Do statement

Case-sensitive variables in "For" statements

In contrast to Unix systems, Windows is usually not case-sensitive, However, iteration variables in "For" statements are case-dependent. So %A is a different variable from %a.

Pin a command-line shortcut to the Start menu

If you use the command prompt frequently, make it easily accessible. Open Start-All Programs-Accessories and right-click the entry "Command Prompt". Select "Pin to Start menu" from the context menu. Or go to \WINDOWS\system32 and right-click the command shell file cmd.exe and select "Pin to Start menu" from the context menu.

Create a shortcut to a command

If there is a command that you use frequently, you can create a shortcut. The trick is to use the switch /k so that the commandprompt stays open. The entry for the shortcut should becmd /k somecommand.exeIf the command also needs switches, those can added as well. (The general details of making a shortcut are at this page.)

Open Windows Explorer from the command line

To open the current command-line directory in a Windows Explorer window use the commandstart .To open the directory above the current command-line directory in a Windows Explorer window use the commandstart ..(Windows XP only) To open My Computer in a Windows Explorer window use the commandstart ...

Using the command "Start"

The tip given above is an example of how the "Start" command can be used to invoke an action or a system folder or an URL. For example, simply entering "cookies" in the Run line will open the system folder Internet Cookies in Windows XP (but not in Vista). However, in the command shell, you would need to enterstart cookiesIn Vista/7, the command has to be modified with the Shell command and would bestart shell:cookiesSimilarly, you can open a program like Microsoft Word with the commandstart winwordYou can also open a Web page in Internet Explorer with a command of the typestart http://somesite.com

Save typing with file-name and folder-name completion (Tab completion)

A very useful feature that can save a lot of typing is the name or path completion function. This feature uses the Tab key to completefile and folder names that you begin typing. For example, type "a" (no quotes) into a command line and then press the Tab key.Windows will complete your typing with the name of an existing file or folder beginning with "a", starting in alphabetic order. Press Tabagain and the next possible file or folder will be displayed. In this way, you can cycle through all files and folders existing in your current path that begin with a particular character or group of characters. The keyboard pair Shift + Tab will take you backwards in the list. The tab completion function can be used in more than one place in a command.

Enable QuickEdit mode for the command window

Being able to cut and paste to and from the command window is very handy but it is not enabled by default. I use this feature frequently and I suggest that you enable it for all command windows. The details of how to enable QuickEdit are given on another page. Once QuickEdit is enabled, the contents of the clipboard can be entered into a command prompt by right-clicking in the command window.

Display the Command History

The default setting for the configuration of a command window includes the capability for storing up to 50 previously entered commands. The command history can be displayed by entering the "F7" key.

Use the "sleep" command in Windows XP batch files

Sometimes it is desirable to have a batch file wait a certain amount of time before it carries out the next command. If you downloadthe free Windows 2003 Server tools (described on another page), one of the available tools is sleep.exe, which provides a way to make batch files wait a specified interval. For an interval of n seconds the command is:sleep n

Copy text from the console window

Way back in the days of DOS, it was not uncommon to enter text directly from the command window into a file with the "copy" command. That is less common in Windows but the capability is still there. Output from the command window or console is denoted by CON. (It is not case-sensitve.) To copy text from the command window to a file "sometext.txt", the sequence of statements would becopy con sometext.txt
First line of your desired text
some more text...
^Z
The last line indicates the keyboard combination of the Control key and "z" followed by pressing the Enter key. This command terminates the sequence and sends the text to the desired file, which it creates. This particular example places the file in the working directory but other paths can be used.

Use Driverquery to list the drivers on your system in a spreadsheet

To create a list of installed drivers in a form that can be read as a spreadsheet, use the command (with administrator privileges)driverquery /v /fo csv > "%userprofile%\drvlist.csv"To list signed drivers usedriverquery /fo csv /si >"%userprofile%\drvlist.csv"

In both cases, the file is placed in the User folder. Modify the location and /or the name of the created file to suit your individual preferences.

(Not available in Windows XP Home)

Tips for the Vista/Windows 7 command shell

Windows XP and Vista/7 share many of the same features in the command line. However, as to be expected, there are some differences. Tips that are relevant to Vista/7 only are given on the next page.

For the most part, the features of the command line are the same in Vista/7 as they are in Windows XP but there are some differences. Here are some tips that apply only to Windows Vista and/or Windows 7.

Run as administrator in Vista/7

The Windows Vista/7 operating system has a security feature calledUser Account Control that limits the privileges of users by default. Since the command line is usually involved with administrative tasks, you'll often want to run as an administrator. This can be done each time by right-clicking the icon for the command prompt and choosing "Run as administrator " from the context menu . A more convenient way is to set the command prompt to run with administrator privileges by default. Right-click the command prompt shortcut icon and choose "Properties" from the context menu. Click the "Advanced" button and put a check by "Run as administrator". Click "OK". Note that you will still get the UAC message when you open the commandprompt.

Another way to run the command prompt as administrator is to enter "cmd" in Start Search and then use the keyboard combinationCtrl+Shift+ Enter.

"Open Command Window Here" in Vista/7

It is now easy to open a command prompt referenced to a folder of your choice in Vista/7. If the Shift key is held down while right-clicking a folder, the context menu will contain an entry, "Open Command Window Here". Selecting this entry will open a commandprompt with the chosen folder as the reference point for commands.

Open command window with administrator privileges anywhere

The "Run as administrator" option mentioned above always opens with \Windows\System 32\ as the working directory. To open a command console with administrator privileges in any directory of choice, you can add a command to the right-click context menu. The INF file to make the appropriate Registry edit can be downloaded here. It is from the PowerToy utility described at this link.

Send command output to the Windows clipboard with clip.exe

Vista/7 comes with a command-line utility clip.exe that can be used to redirect or pipe the output of another command to theWindows clipboard. The command uses a "pipe" and has the form:somecommand | clipFor example, to send a directory listing to the clipboard, the command is:dir | clip

Place the contents of a text file into the Windows clipboard with clip.exe

The utility clip.exe can also be used to read a text file and place its contents in the Windows clipboard. The command has the form:clip < somefile.txt

Clear the Windows clipboard with clip.exe

To clear the contents of the Windows clip board, use a "pipe" :echo off | clip

The batch file command called "choice" is back in Vista/7

Oldtimers will remember that DOS had a command for batch files called "choice" that allowed for some limited user interaction. The command was then removed from 32-bit command shells because the "set /p" option gave equivalent or better functionality. However, "choice" is back in Vista/7 in a new form. Enter "choice /?" in a Vista/7 command prompt for details about its features.

Use the "choice" command to make a Vista/7 batch file wait

One useful application of the "choice" command is to make a batch file pause for a specified period of time. The statement has the form:choice /T n /D y > nulThe switch "/T n" specifies a wait period of n seconds. The switch "/D y" creates a default choice of "yes". To suppress the unwanted text output of the command, it is redirected to the null device (nul).

Use the "timeout" command to make a Vista/7 batch file wait

Another new command in in Vista/7 is "timeout". It will cause the command processor to wait for a specified number of seconds or until a key is pressed. The format istimeout /T nwhere n is the number of seconds to wait. To make the command ignore any key presses, the switch /nobreak can be added:timeout /T n /nobreakBecause the command gives output listing the time remaining, it may be necessary to use a redirect to nul.timeout /T n > nul

Switch added to "Dir" to enable viewing Alternate Data Streams

NTFS files can have added information in "streams" or "forks". These added items are normally hidden from access by mostWindows functions such as Explorer. In Vista/7 a switch /R has been added to the "dir" command that allows alternate data streams to be listed.

Enable the built-in master administrator account on the log-in screen

Vista/7 contain a master administrator account but it is not normally visible on the log-in screen. To enable it, open a command window with administrator privileges and use the commandnet user administrator /active:yes(Make sure that you assign a password to the account.) To remove the account from the log-in screen, use the commandnet user administrator /active:no

Increase the file system memory cache with fsutil

If you tend to open and close a lot of files, you may be able to increase performance by creating a larger value for a special cache setting with the file system utility commandfsutil behavior set memoryusage 2According to Microsoft, this increases something called the "paged pool" memory. Do not use if you are already consuming large amounts of system memory with other activities. If performance after the change is unsatisfactory, undo it with the commandfsutil behavior set memoryusage 1These commands require administrator privileges. The commands change a Registry setting and take effect after a reboot.

Use "takeown" to access certain files

Vista/7 protects many system files for security reasons and even an administrator may not allowed to access certain of them. If you are denied access to a file while in an administrator account, you can use the command line tool "takeown.exe" to reassign ownership. You will need to run the command from a command prompt with administrator privileges. The syntax istakeown /f some_file [/a] [/r]The specified filename can contain wildcards. You can also specify a folder. The optional switch "/a" transfers ownership to the administrators group. If omitted, the default is to transfer ownership to the present user account. The switch "/r" recurses subdirectories. Although this command assigns ownership, it does not give control rights. Thus if you wish to modify a system file(often not a good idea) you will probably have also to apply the "icacls" command discussed next.

Obtain control rights to a file with "icacls"

(Icacls.exe supersedes the "cacls" command of Windows XP. The older command is still available, however.) This command has a rather complex set of options. They can be displayed by entering "icacls /?" in a command prompt. One example is the command to grant full access rights to an account named user:icacls file_name /grant user:F

Using drag and drop- no in Vista, yes in Windows 7

The useful capability to drag commands and drop them into a command prompt that was present in past versions of Windows does not work in Vista. However, it has been restored in Windows 7.

Vssadmin tips

Information about Vssadmin has been expanded to a full page that can be found at this link. 

posted on 2012-05-09 00:42  岌岌可危  阅读(300)  评论(0编辑  收藏  举报