DESKTOP

Batch File Basics (Part 3)

10/9/2012 3:35:47 AM

Using More Variables

So how can we combine this batch file with the first example we looked at, that printed off the directory listing? We could, for instance, ask the user what folder they would like the directory listing of, choosing from the currently available selection. Try this:

@echo off

cls

dir "c:\" > list.txt

type list.txt

echo.

echo From the list, which folder would you like to view?

set /p view= (enter as c:\folder)

dir "%view%" > view.txt

notepad.exe view.txt

cls

del /Q view.txt

del /Q list.txt

This batch file, when saved and executed as an Administrator (due to the UAC and the piping of protected folders) will list the folders on your PC from the root level, then pipe them into a file called list.txt. Then, using the type command, we can output the contents of list.txt, and with a blank echo command we can create a blank line, followed by the text output 'From the list...'

Next we have the set /p command we used earlier, but this time creating a variable called %view%, which we use as the input to pipe the dir. command into a text file (view.txt) which we open in Notepad.

The end of the batch file cleans up the extra files we created, and clears the screen.

Description: When you're asking the OS to look at a protected folder, you're going to require Administrator privileges
When you're asking the OS to look at a protected folder, you're going to require Administrator privileges

More Fun with Variables

This next batch file will pull together everything we've done so far, plus add a few extras including color!

Here's the scenario, we want to search our hard drive (the c:\ drive in this instance) for certain types of files, be they MP3, JPG, DOC or whatever, but we want the user to be able to choose what type of file to search for. In DOS there's a handy command called where, which will hunt out files and display them, providing of course the correct syntax has been used. And there's another command that will change the colors of the output, called color (American spelling, I know).

Open up Notepad, and create a new batch file, with the following script:

@echo off

cls

color 2

echo Please enter the type of file you want to search for (MP3, DOC, JPG for example)

echo.

set /p ext= where /R c:\ *.%ext% > found.txt notepad.exe found.txt

cls

color

del /Q found.txt

Skipping the bits we already know, the first command we get to is color. The color attributes are specified by two hex digits, the first corresponds to the background color of the Command console, and the second to the foreground, and can be any of the following values:

0 = Black

1 = Blue

2 = Green

3 = Aqua

4 = Red

5 = Purple

6 = Yellow

7 = White

8 = Grey

9 = Light Blue

A = Light Green

B = Light Aqua

C = Light Red

D = Light Purple

E = Light Yellow

F = Bright White

In our case it will keep the background as black, but change the text to green. Again we use the set /p command, but this time we leave it blank, for the user to type in, but creating the variable %ext%. The next command is the aforementioned where, and the /R switch. Basically, the where command is the equivalent to the Unix 'which' command and will search the default current directory, then any other directories as specified in the Path setting of Windows. By using the /R switch we can perform a recursive search within the C:\ drive, as we specified. The remainder of the where command contains a wildcard, the *, then the variable of what file extension we want to search for, %ext%, followed by piping the output into a text file called found.txt.

Finally, we show the results of the text file in Notepad, clear the screen, reset the color back to the default, by issuing color without any attributes, and clean up after ourselves.

All in all, that's a fairly handy batch file we've created, and although it may never replace the Windows search function it's still good to know what can be accomplished via the Command prompt and a bit of simple batch scripting.

To run the batch file, you'll have to be Administrator again, and you can either execute it via the admin Command prompt, or from the 'Run as...' right click menu selection from within Windows. Type in a file extension to search for - case isn't important - and hit Enter. Depending on the size of the drive, and how many files it finds the results should be shown within a minute or so.

Description: Color, variables and an output to a text file that's auto-opened in Notepad. Cool
Color, variables and an output to a text file that's auto-opened in Notepad. Cool

One Last Modification

Before we sign off for this week, let's have a quick look at a small modification we can make to the above batch file. Let's say you have more than one drive, C:\ and D:\, and you want to specify which drive to search from. As most of you have probably already worked out, just add the following extra variable to the script:

@echo off

cls

color 2

echo Please enter the type of file you want to search for(MP3, DOC, JPG for example) echo.

set /p ext= echo.

echo And which drive do you want search within? (C or D) set /p drive= where /R %drive%:\ *. %ext% > found.txt

notepad.exe found.txt

cls

color

del /Q found.txt

All we are doing is adding a variable %drive% which will input the users' choice of 'C' or 'D' into the where command.

Next Week

That's it for this week. Next week we'll have a look at creating a basic menu, a few more variables, go to, if and else.

Windows 7 Command List

With each new version of Windows that's released, commands come, and commands go. Within Windows 7, the current list of commands is (courtesy of Microsoft):

ASSOC Displays or modifies file extension associations.

ATTRIB Displays or changes file attributes. BREAK Sets or clears extended CTRL+C checking.

BCDBOOT Used to copy critical files to the system partition and to create a new system BCD store.

BCDEDIT sets properties in boot database to control boot loading.

CACLS Displays or modifies access control lists (ACLs) of files.

CALL Calls one batch program from another.

CD Displays the name of or changes the current directory.

CHCP Displays or sets the active code page number.

CHDIR Displays the name of or changes the current directory.

CHKDSK Checks a disk and displays a status report.

CHKNTFS Displays or modifies the checking of disk at boot time.

CHOICE Batch file command that allows users to select from a set of options.

CIPHER Displays or alters the encryption of directories [files] on NTFS partitions.

CLIP Redirects output of another command to the Windows clipboard.

CLS clears the screen.

CMD Starts a new instance of the Windows command interpreter.

CMDKEY Creates lists and deletes stored user names and passwords or credentials. COLOR Sets the default console foreground and background colors.

COMP Compares the contents of two files or sets of files byte-by-byte COMPACT Displays or alters the compression of files on NTFS partitions. CONVERT Converts FAT volumes to NTFS.

You cannot convert the current drive.

COPY Copies one or more files to another location.

DATE Displays or sets the date.

DEFRAG Disk defragmenter accessory.

DEL Deletes one or more files.

DIR displays a list of files and subdirectories in a directory.

DISKCOMP compares the contents of two floppy disks.

DISKCOPY Copies the contents of one floppy disk to another.

DISKPART Displays or configures Disk Partition properties. Separate commands to interpreter with a sub-set of commands. DOSKEY Edits command lines, recalls Windows commands, and creates macros.

DRIVERQUERY Displays current device driver status and properties.

ECHO Displays messages, or turns command echoing on or off.

ENDLOCAL Ends localization of environment changes in a batch file. ERASE deletes one or more files.

EXIT Quits and closes the command shell. EXPAND Expands one or more compressed files.

FC Compares two files or sets of files, and displays the differences between them.

FIND Searches for a text string in a file or files.

FINDSTR Searches for strings in files.

FOR Runs a specified command for each item in a set.

FORFILES Selects files in a folder for batch processing.

FORMAT formats a disk for use with Windows.

FSUTIL Displays or configures the file system properties.

FTYPE Displays or modifies file types used in file extension associations.

GOTO Directs the Windows command interpreter to a labeled line in a batch program.

GPRESULT Displays Group Policy is information for machine or user. GRAFTABL Enables Windows to display an extended character set in graphics mode.

HELP Provides Help information for Windows commands.

ICACLS Display, modify, backup, or restore ACLs for files and directories.

IF Performs conditional processing in batch programs.

IPCONFIG Displays all current TCP/IP network configuration values LABEL Creates, changes, or deletes the volume label of a disk.

MD Creates a directory.

MKDIR creates a directory.

MKLINK Creates Symbolic Links and Hard Links

MODE configures a system device.

MORE displays output one screen at a time.

MOVE Moves one or more files from one directory to another directory.

OPENFILES Queries, displays, or disconnects open files or files opened by network users.

PATH Displays or sets a search path for executable files.

PAUSE Suspends processing of a batch file and displays a message.

POPD Restores the previous value of the current directory saved by PUSHD.

PRINT Prints a text file.

PROMPT Changes the Windows command prompt.

PUSHD Saves the current directory then changes it.

RD Removes a directory.

RECOVER Recovers readable information from a bad or defective disk.

REM Designates comments (remarks) in batch files

REN Renames a file or files.

RENAME Renames a file or files.

REPLACE Replaces files.

RMDIR removes a directory.

ROBOCOPY Advanced utility to copy files and directory trees SET Displays, sets, or removes environment variables for current session. SETLOCAL Begins localization of environment changes in a batch file.

SETX set environment variables.

SC Displays or configures services (background processes).

SCHTASKS Schedules commands and programs to run on a computer.

SHIFT Shifts the position of replaceable parameters in batch files.

SHUTDOWN Allows proper local or remote shutdown of machine.

SORT Sorts input.

START starts a separate window to run a specified program or command.

SUBST Associates a path with a drive letter.

SYSTEMINFO Displays machine specific properties and configuration.

TAKEOWN allows an administrator to take ownership of a file.

TASKLIST Displays all currently running tasks including services.

TASKKILL Kill or stop a running process or application.

TIME Displays or sets the system time. TIMEOUT pauses the command processor for the specified number of seconds.

TITLE sets the window title for a CMD. EXE session.

TREE graphically displays the directory structure of a drive or path.

TYPE displays the contents of a text file. VER Displays the Windows version.

VERIFY Tells Windows whether to verify that your files are written correctly to a disk.

VOL displays a disk volume label and serial number.

VSSADMIN Volume Shadow Copy Service administration tool

WHERE display the location of files that match a search pattern.

Other  
 
Most View
Spring Is Here (Part 2)
Is 802.11ac Worth Adopting?
BlackBerry Z10 - A Touchscreen-Based Smartphone (Part 1)
LG Intuition Review - Skirts The Line Between Smartphone And Tablet (Part 5)
Fujifilm X-E1 - A Retro Camera That Inspires (Part 4)
My SQL : Replication for High Availability - Procedures (part 6) - Slave Promotion - A revised method for promoting a slave
10 Contenders For The 'Ultimate Protector' Crown (Part 3) : Eset Smart Security 6, Kaspersky Internet Security 2013, Zonealarm Internet Security 2013
HTC Desire C - Does It Have Anything Good?
Windows Phone 7 : Understanding Matrix Transformations (part 2) - Applying Multiple Transformations
How To Lock Windows By Image Password
REVIEW
- First look: Apple Watch

- 10 Amazing Tools You Should Be Using with Dropbox
VIDEO TUTORIAL
- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 1)

- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 2)

- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 3)
Popular Tags
Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Biztalk Exchange Server Microsoft LynC Server Microsoft Dynamic Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 Adobe Indesign Adobe Flash Professional Dreamweaver Adobe Illustrator Adobe After Effects Adobe Photoshop Adobe Fireworks Adobe Flash Catalyst Corel Painter X CorelDRAW X5 CorelDraw 10 QuarkXPress 8 windows Phone 7 windows Phone 8 BlackBerry Android Ipad Iphone iOS
Top 10
OPEL MERIVA : Making a grand entrance
FORD MONDEO 2.0 ECOBOOST : Modern Mondeo
BMW 650i COUPE : Sexy retooling of BMW's 6-series
BMW 120d; M135i - Finely tuned
PHP Tutorials : Storing Images in MySQL with PHP (part 2) - Creating the HTML, Inserting the Image into MySQL
PHP Tutorials : Storing Images in MySQL with PHP (part 1) - Why store binary files in MySQL using PHP?
Java Tutorials : Nested For Loop (part 2) - Program to create a Two-Dimensional Array
Java Tutorials : Nested For Loop (part 1)
C# Tutorial: Reading and Writing XML Files (part 2) - Reading XML Files
C# Tutorial: Reading and Writing XML Files (part 1) - Writing XML Files