Programming4us
         
 
 
Windows

Windows 7 : Working with the Command-Line Tools (part 2) - Working with File and Folder Management Tools

12/7/2010 11:21:21 AM

Working with File and Folder Management Tools

Windows Explorer is the GUI tool of choice for most file and folder operations. However, Windows 7 comes with an impressive collection of command-line file and folder tools that let you perform all the standard operations such as renaming, copying, moving, and deleting, as well as more interesting chores such as changing file attributes and comparing the contents of two files. Table 2 lists the file management tools that you can use with Windows 7.

Table 2. Windows 7’s Command-Line File and Folder Management Tools
ToolDescription
ATTRIBDisplays, applies, or removes attributes for the specified file or folder.
CDChanges to the specified folder.
COMPCompares the contents of two specified files byte by byte.
COMPACTDisplays or modifies the compression settings for the specified file or folder (which must be located on an NTFS partition).
COPYCreates a copy of the specified file or folder in another location.
DELDeletes the specified file or folder.
DIRDisplays a directory listing for the current folder or for the specified file or folder.
FCCompares the content of two specified files.
FINDSearches for and displays all the instances of a specified string in a file.
FINDSTRUses a regular expression to search for and display all the instances of a specified string in a file.
MKDIRCreates the specified folder.
MOVEMoves the specified file or folder to another location.
RENChanges the name of the specified file or folder.
REPLACEReplaces files in the destination folder with files in the source folder that have the same name.
RMDIRDeletes the specified folder.
SORTSorts the specified file and then displays the results.
SFCRuns the System File Checker, which scans and verifies the protected Windows 7 files.
TAKEOWNEnables an administrator to take ownership of the specified file.
TREEDisplays a graphical tree diagram showing the subfolder hierarchy of the current folder or the specified folder.
WHERESearches for and displays all the files that match a specified pattern in the current folder and in the PATH folders.
XCOPYCreates a copy of the specified file or folder in another location. This tool offers many more options than the COPY command.

The next few sections take a closer look at a half dozen of these tools: ATTRIB, FIND, REN, REPLACE, SORT, and XCOPY.

Before getting to the tools, I should mention that most of the file and folder management tools work with the standard wildcard characters: ? and *. In a file or folder specification, you use ? to substitute for a single character, and you use * to substitute for multiple characters. Here are some examples:

File SpecificationMatches
Budget200?.xlsxBudget2009.xlsx, Budget2008.xlsx, and so on
Memo.doc?Memo.doc, Memo.docx, Memo.docm, and so on
*.txtReadMe.txt, log.txt, to-do.txt, and so on
*200?.pptxReport2009.pptx, Budget2007.pptx, Conference2008.pptx, and so on
*.*Every file

ATTRIB: Modifying File and Folder Attributes

A file’s attributes are special codes that indicate the status of the file. There are four attributes you can work with:

  • Archive— When this attribute is turned on, it means the file has been modified since it was last backed up.

  • Hidden— When this attribute is turned on, it means the file doesn’t show up in a DIR listing and isn’t included when you run most command-line tools. For example, if you run DEL *.* in a folder, Windows 7 deletes all the files in that folder, except the hidden files.

  • Read-only— When this attribute is turned on, it means the file can’t be modified or erased.

  • System— When this attribute is turned on, it means the file is an operating system file (that is, a file that was installed with Windows 7).

The ATTRIB command lets you turn these attributes on or off. Here’s the syntax:

ATTRIB [+A | -A] [+H | -H] [+R | -R] [+S | -S] filename [/S [/D]]

+ASets the archive attribute
-AClears the archive attribute
+HSets the hidden attribute
-HClears the hidden attribute
+RSets the read-only attribute
-RClears the read-only attribute
+SSets the system attribute
-SClears the system attribute
filenameThe file or files you want to work with
/SApplies the attribute change to the matching files in the current folder and all of its subfolders
/DApplies the attribute change only to the current folder’s subfolders. You must use this switch in conjunction with /S

For example, if you want to hide all the DOC files in the current directory, use the following command:

attrib +h *.doc

As another example, if you’ve ever tried to delete or edit a file and got the message Access denied, the file is likely read-only. You can turn off the read-only attribute by running ATTRIB with the -R switch, as in this example:

attrib -r readonly.txt

Note

If you want to check out a file’s attributes, use the DIR command’s /A switch. Use /AA to see files with their archive attribute set, /AH for hidden files, /AR for read-only, and /AS for system files.


You can also use ATTRIB for protecting important or sensitive files. When you hide a file, it doesn’t show up in a listing produced by the DIR command. Out of sight is out of mind, so someone taking a casual glance at your files won’t see the hidden ones and, therefore, won’t be tempted to display or erase them.

Although a hidden file is invisible, it’s not totally safe. Someone who knows the name of the file can attempt to modify the file by opening it with the appropriate program. As an added measure of safety, you can also set the file’s read-only attribute. When you do this, the file can’t be modified. You can set both attributes with a single command:

attrib +h +r payroll.xlsx

FIND: Locating a Text String in a File

You use the FIND command to search for a string inside a file. Here’s the syntax:

FIND [/C] [/I] [/N] [/V] "string" filename

/CDisplays the number of times that string appears in filename.
/IPerforms a case-insensitive search.
/NDisplays each match of string in filename with the line number in filename where each match occurs.
/VDisplays the lines in filename that don’t contain string.
stringThe string you want to search for.
filenameThe file you want to search in. (Note that you can’t use wildcards with the FIND command.) If the filename contains one or more spaces, surround it with double quotation marks.

Note

The FIND command doesn’t work with the new Office 2007 file formats. However, it works fine with most documents created in earlier versions of Office.


For example, to find the string DVD in a file named WishList.txt, you use the following command:

find "DVD" WishList.txt

If the string you want to find contains double quotation marks, you need to place two quotation marks in the search string. For example, to find the phrase Dave “The Hammer” Schultz in the file players.doc, use the following command:

find "Dave ""The Hammer"" Schultz" players.doc

Tip

The FIND command doesn’t accept wildcard characters in the filename parameter. That’s too bad, because it’s often useful to search multiple files for a string. Fortunately, you can work around this limitation by using a FOR loop where the command you run on each file is FIND. Here’s the general syntax to use:

FOR %f IN (filespec) DO FIND "string" %f

Replace filespec with the file specification you want to use, and string with the string you want to search for. For example, the following command runs through all the .doc files in the current folder and searches each file for the string Thanksgiving:

FOR %f IN (*.doc) DO FIND "Thanksgiving" %f

If the file specification will match files with spaces in their names, you need to surround the last %f parameter with quotation marks, like so:

FOR %f IN (*.doc) DO FIND "Thanksgiving" "%f"


One of the most common uses of the FIND command is as a filter in pipe operations . In this case, instead of a filename, you pipe the output of another command through FIND. In this case, FIND searches this input for a specified string and, if it finds a match, it displays the line that contains the string.

For example, the last line of a DIR listing tells you the number of bytes free on the current drive. Rather than wade through the entire DIR output just to get this information, use this command instead:

dir | find "free"

You’ll see something like the following:

2 Dir(s) 28,903,331,184 bytes free

FIND scours the DIR listing piped to it and looks for the word free. You can use this technique to display specific lines from, say, a CHKDSK report. For example, searching for bad finds the number of bad sectors on the disk.

REN: Renaming a File or Folder

You use the REN (or RENAME) command to change the name of one or more files and folders. Here’s the syntax:

REN old_filename1 new_filename

old_filenameThe original filename
new_filenameThe new filename

For example, the following command renamed Budget 2007.xlsx to Budget 2008.xlsx:

ren "Budget 2007.xlsx" "Budget 2008.xlsx"

A simple file or folder rename such as this probably isn’t something you’ll ever fire up a command-line session to do because renaming a single object is faster and easier in Windows Explorer. However, the real power of the REN command is that it accepts wildcards in the file specifications. This enables you to rename several files at once, something you can’t do in Windows Explorer.

For example, suppose you have a folder full of files, many of which contain 2009 somewhere in the filename. To rename all those files by changing 2009 to 2010, you’d use the following command:

ren *2009* *2010*

Similarly, if you have a folder full of files that use the .htm extension and you want to change each extension to .asp, you use the following command:

ren *.htm *.asp

Note that for these multiple-file renames to work, in most cases the original filename text and the new filename text must be the same length. For example, digital cameras often supply photos with names such as img_1234.jpg and img_5678.jpg. If you have a number of related photos in a folder, you might want to give them more meaningful names. If the photos are from a vacation in Rome, you might prefer names such as Rome_Vacation_1234.jpg and Rome_Vacation_5678.jpg. Unfortunately, the REN command can’t handle this. However, it can rename the files to Rome_1234.jpg and Rome_5678.jpg:

ren img_* Rome*

The exception to the same length rule is if the replacement occurs at the end of the filenames. For example, the following command renames all files with the .jpeg extension to

.jpg:

ren *.jpeg *.jpg

REPLACE: Smarter File Copying

If there was such a thing as a Most Underrated Command award, REPLACE would win it hands down. This command, which you almost never hear about, can do three very useful (and very different) things:

  • It copies files, but only if their names match those in the target directory.

  • It copies files, but only if their names don’t exist in the target directory.

  • It copies files, but only if their names match those in the target directory and the matching files in the target directory are older than the files being copied.

Here’s the syntax:

REPLACE source_files target /A /U /P /R /S /W

source_filesThe path and file specification of the files you want to copy.
targetThe folder to which you want to copy the files.
/ACopies only new files to the target folder. You can’t use this switch in conjunction with /S or /U.
/UCopies files that have the same name in the target folder and that are newer than the matching files in the target folder. You can’t use this switch in conjunction with /A.
/PPrompts you for confirmation before replacing files.
/RReplaces read-only files.
/SReplaces files in the target folder’s subfolders. You can’t use this switch in conjunction with /A.
/WWaits for you to insert a disk before starting.

If you don’t specify switches, REPLACE copies a file from the source folder to the target folder if and only if it finds a file with a matching name in the target.

More useful is the REPLACE command’s updating mode, where it copies a file from the source folder to the target folder if and only if it finds a file with a matching name in the target and that target file is older than the source file. A good example where updating comes in handy is when you copy some files to a disk or memory card so that you can use them on another machine (such as taking files from your computer at work to use them at home). When you need to copy the files back to the first machine, the following REPLACE command does the job. (This assumes the disk or memory card is in the G: drive.)

replace g:*.* %UserProfile% /s /u

For each file on the G: drive, REPLACE looks for matching filenames anywhere in the %UserProfile% folder and its subfolders (thanks to the /S switch) and replaces only the ones that are newer (the /U switch).

What if you created some new files on the other computer? To copy those to the first machine, use the /A switch, as follows:

replace g:*.* %UserProfile%\Documents /a

In this case, REPLACE only copies a file from the G: drive if it doesn’t exist in the %UserProfile%\Documents folder. (You have to specify a target folder because you can’t use the /S switch with /A.)

SORT: Sorting the Contents of a File

When you obtain a file from the Internet or some other source, the data in the file may not appear in the order you want. What I usually do in such cases is import the file into Word or Excel and then use the program’s Sort feature. This sometimes involves extra steps (such as converting text to a table in Word), so it’s not always an efficient way to work.

If the file is text, it’s often easier and faster to run the SORT command-line tool. By default, SORT takes the content of the file, sorts it in ascending alphanumeric order (0 to 9, then a to z, and then A to Z) starting at the beginning of each line in the file, and then displays the sorted results. You can also run descending order sorts, write the results to the same file or another file, and more. Here’s the syntax:

SORT [input_file] [/+n] [/R] [/L locale] [/M kilobytes] [/REC characters] [/T temp_folder] [/O output_file]


input_fileThe file you want to sort.
/+nSpecifies the starting character position (n) of the sort. The default is 1 (that is, the first character on each line in the file).
/RSorts the file in descending order (Z to A, then z to a, and then 9 to 0).
/L localeSpecifies a locale for sorting other than the default system locale. Your only choice here is to use "C" to sort the file using the binary values for each character.
/M kilobytesSpecifies the amount of memory, in kilobytes, that SORT uses during the operation. If you don’t specify this value, SORT uses a minimum of 160KB and a maximum of 90% of available memory.
/REC charactersSpecifies the maximum length, in characters, of each line in the file. The default value is 4,096 characters, and the maximum value is 65,535 characters.
/T temp_folderSpecifies the folder that SORT should use to hold the temporary files it uses during the sort.
/O output_fileSpecifies the file that SORT should create to store the results of the sort. You can specify a different file or the input file.

For example, the following SORT command sorts the data in records.txt and stores the results in sorted_records.txt:

sort records.txt sorted_records.txt

XCOPY: Advanced File Copying

The XCOPY command is one of the most powerful of the file management command-line tools, and you can use it for some fairly sophisticated file copying operations. Here’s the syntax for XCOPY:

XCOPY source destination [/A | /M] [/C] [/D[:mm-dd—yyyy]] [/EXCLUDE:file1[+file2[+file3]]] [/F] [/G] [/H] [/I] [/K] [/L] [/N] [/O] [/P] [/Q] [/R] [/S [/E]] [/T] [/U] [/V] [/W] [/X] [/Y | -Y] [/Z]


sourceThe path and names of the files you want to copy.
destinationThe location where you want the source files copied.
[/A]Tells XCOPY to only copy those source files that have their archive attribute turned on. The archive attribute is not changed. If you use /A, you can’t also use /M.
[/M]Tells XCOPY to only copy those source files that have their archive attribute turned on. The archive attribute is turned off. If you use /M, you can’t also use /A.
[/C]Tells XCOPY to ignore any errors that occur during the copy operation. Otherwise, XCOPY aborts the operation if an error occurs.
[/D[:mm-dd-yyyy]]Copies only those source files that changed on or after the date specified by mm-dd-yyyy. If you don’t specify a date, using /D tells XCOPY to copy those source files that are newer than destination files that have the same name.
[/EXCLUDE:file1[+file2[+file3]]] Tells XCOPY to not copy the files or file specification given by file1, file2, file3, and so on.
[/F]Displays the source and destination filename during the copy operation.
[/G]Creates decrypted copies of encrypted source files.
[/H]Tells XCOPY to include in the copy operation any hidden and system files in the source folder.
[/I]Tells XCOPY to create the destination folder. For this to work, the source value must be a folder or a file specification with wildcards.
[/K]For each source file that has its read-only attribute set, tells XCOPY to maintain the read-only attribute on the corresponding destination file.
[/L]Displays a list of the files that XCOPY will copy. (No files are copied if you use /L.)
[/N]Tells XCOPY to use 8.3 filenames in the destination folder. Use this switch if the destination folder is a FAT partition that doesn’t support long filenames.
[/O]Tells XCOPY to also copy ownership and discretionary access control list data to the destination.
[/P]Prompts you to confirm each file copy.
[/Q]Tells XCOPY not to display messages during the copy.
[/R]Includes read-only files in the copy.
[/S]Tells XCOPY to also include the source folder’s subfolders in the copy.
[/E]Tells XCOPY to include empty subfolders in the copy if you specify the /S/T switch. or
[/T]Tells XCOPY to copy the source folder subfolder structure. (No files are copied, just the subfolders.)
[/U]Only copies those source files that exist in the destination folder.
[/V]Tells XCOPY to verify that each destination copy is identical to the original source file.
[/W]Displays the message Press any key to begin copying file(s) before copying. You must press a key to launch the copy (or press Ctrl+C to cancel).
[/X]Tells XCOPY to also copy file audit settings and system access control list data to the destination. (This switch implies /O.)
[/Y]Tells XCOPY not to ask you whether you want to overwrite existing files in the destination.
[/-Y]Tells XCOPY to ask you whether you want to overwrite existing files in the destination. Use this switch if you’ve set the %COPYCMD%/Y, which suppresses overwrite prompts for XCOPY, COPY, and MOVE. environment variable to
[/Z]If you’re copying to a network destination, this switch tells XCOPY to restart to the copy if the network connection goes down during the operation.

In its basic form, XCOPY works just like COPY. So, for example, to copy all the .doc files in the current folder to a folder called Documents in the G: drive, use the following command:

xcopy *.doc g:\documents

Besides being faster, XCOPY also contains a number of features not found in the puny COPY command. Think of it as COPY on steroids. (The X in XCOPYCOPY command.) For example, suppose you want to copy all the .doc files in the current folder and all the .doc files in any attached subfolders to G:\Documents. With COPY, you first have to create the appropriate folders on the destination partition and then perform separate COPY commands for each folder, which is not very efficient, to say the least. With XCOPY, all you do is add a single switch: means that it’s an extended

xcopy *.doc g:\documents /s
xcopy *.bat d:\batch /s

The /S switch tells XCOPY to copy the current folder and all nonempty subfolders, and to create the appropriate folders in the destination, as needed. (If you want XCOPY to copy empty subfolders, include the /E switch, as well.)

Another useful feature of XCOPY is the ability to copy files by date. This is handy for performing incremental backups of files that you modified on or after a specific date. For example, suppose you keep your word processing documents in %UserProfile%\Documents and you want to make backup copies in your Windows 7 user share of all the .doc files that have changed since August 23, 2007. You can do this with the following command:

xcopy %userprofile%\documents\*.doc \\server\users\%Username%\ /d:08-23-2007

It’s common to use XCOPY in batch files, but take care to handle errors. For example, what if a batch file tries to use XCOPY, but there’s not enough memory? Or what if the user presses Ctrl+C during the copy? It might seem impossible to check for these kinds of errors; yet it is not only possible, it’s really quite easy.

When certain commands finish, they always file a report on the progress of the operation. This report, or exit code, is a number that specifies how the operation went. For example, Table 3 lists the exit codes that the XCOPY command uses.

Table 3. XCOPY Exit Codes
Exit CodeWhat It Means
0Everything’s okay; the files were copied.
1Nothing happened because no files were found to copy.
2The user pressed Ctrl+C to abort the copy.
4The command failed because there wasn’t enough memory or disk space or because there was something wrong with the command’s syntax.
5The command failed because of a disk error.

What does all this mean for your batch files? You can use a variation of the IF command—IF ERRORLEVEL—to test for these exit codes. For example, here’s a batch file called CheckCopy.bat, which uses some of the XCOPY exit codes to check for errors:

@ECHO OFF
XCOPY %1 %2
IF ERRORLEVEL 4 GOTO ERROR
IF ERRORLEVEL 2 GOTO CTRL+C
IF ERRORLEVEL 1 GOTO NO_FILES
GOTO DONE
:ERROR
ECHO Bad news! The copy failed because there wasn't
ECHO enough memory or disk space or because there was
ECHO something wrong with your file specs . . .
GOTO DONE
:CTRL+C
ECHO Hey, what gives? You pressed Ctrl+C to abort . . .
GOTO DONE
:NO_FILES
ECHO Bad news! No files were found to copy . . .
:DONE

As you can see, the ERRORLEVEL conditions check for the individual exit codes and then use GOTO to jump to the appropriate label.

Note

How does a batch file know what a command’s exit code was? When Windows 7 gets an exit code from a command, it stores it in a special data area set aside for exit code information. When Windows 7 sees the IF ERRORLEVEL command in a batch file, it retrieves the exit code from the data area so that it can be compared to whatever is in the IF condition.


One of the most important things to know about the IF ERRORLEVEL test is how Windows 7 interprets it. For example, consider the following IF command:

IF ERRORLEVEL 2 GOTO CTRL+C

Windows 7 interprets this command as “If the exit code from the last command is equal to or greater than 2, jump to the CTRL+C label.” This has two important consequences for your batch files:

  • The test IF ERRORLEVEL 0 doesn’t tell you much because it’s always true. If you just want to find out whether the command failed, use the test IF NOT ERRORLEVEL 0.

  • To get the correct results, always test the highest ERRORLEVEL first and then work your way down.

Other -----------------
- SOA with .NET and Windows Azure : System.Transactions
- Windows 7 : Understanding Batch File Basics (part 2) - Using Batch File Parameters
- Windows 7 : Understanding Batch File Basics (part 1) - Creating Batch Files
- Discovering the Microsoft Azure Platform
- SOA with .NET and Windows Azure : Microsoft Messaging Queue (MSMQ)
- Windows 7 : Working at the Command Line (part 3)
- Windows 7 : Working at the Command Line (part 2)
- Windows 7 : Working at the Command Line (part 1)
- Windows 7 : Getting to the Command Line (part 2) - Running CMD
- Windows 7 : Getting to the Command Line (part 1)
- Windows Azure : Programming Access Control Service (part 10) - Deploying the Web Service in Windows Azure
- Windows Azure : Programming Access Control Service (part 9) - Configuring a Web Service Client to Acquire and Send SAML Tokens
- Windows Azure : Programming Access Control Service (part 8)
- Windows Azure : Programming Access Control Service (part 7) - Integrating ACS with a SAML Token Provider
- Windows Azure : Programming Access Control Service (part 6)
- Windows Azure : Programming Access Control Service (part 5)
- Windows Azure : Programming Access Control Service (part 4)
- Windows Azure : Programming Access Control Service (part 3)
- Windows Azure : Programming Access Control Service (part 2)
- Windows Azure : Programming Access Control Service (part 1)
 
 
Most View
- BizTalk Server 2009 : The core principles of a service-oriented architecture (part 2)
- Programming WCF Services : The Response Service (part 3) - Queued Service-Side Programming & Response Service-Side Programming
- Implementing Edge Services for an Exchange Server 2007 Environment : Utilizing the Basic Sender and Recipient Connection Filters (part 1)
- Windows Phone 7 Game Development : Orthographic Projection (part 1) - The Viewing Frustum & Defining the Orthographic Viewing Frustum in XNA
- Required Project Images for iPad Apps
- Build Mobile Websites and Apps for Smart Devices : Design for Mobile - Build a Better Mouse
- iPhone Programming : Connecting to the Network - Sending Email
- iPad SDK : Preparing Dudel for a New Tool (part 4) - Creating a New Drawable Class
- Windows Vista : Working with Windows Deployment Services (part 1) - Creating a Capture image, Creating a Custom Install image
- Windows 7: Managing Your Hardware with Device Manager (part 1)
Top 10
- Implementing Edge Services for an Exchange Server 2007 Environment : Utilizing the Basic Sender and Recipient Connection Filters (part 3) - Configuring Recipient Filtering
- Implementing Edge Services for an Exchange Server 2007 Environment : Utilizing the Basic Sender and Recipient Connection Filters (part 2)
- Implementing Edge Services for an Exchange Server 2007 Environment : Utilizing the Basic Sender and Recipient Connection Filters (part 1)
- Implementing Edge Services for an Exchange Server 2007 Environment : Installing and Configuring the Edge Transport Server Components
- What's New in SharePoint 2013 (part 7) - BCS
- What's New in SharePoint 2013 (part 6) - SEARCH
- What's New in SharePoint 2013 (part 6) - WEB CONTENT MANAGEMENT
- What's New in SharePoint 2013 (part 5) - ENTERPRISE CONTENT MANAGEMENT
- What's New in SharePoint 2013 (part 4) - WORKFLOWS
- What's New in SharePoint 2013 (part 3) - REMOTE EVENTS