Solved

Batch Files 101:  An Introduction

Posted on 2004-10-09
27
1,972 Views
Last Modified: 2012-08-14
I want to learn how to write batch files in general and how to assign them as startup or logon scripts in my security policy in Windows XP

For example, something that clears my I.E. cache everytime I boot up.

Can someone introduce me to the art of writing batch files for fun and also give me a practcal example of one that would clear my I.E. cache at user logon?

Below is something I might need for reference:
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds.mspx



0
Comment
Question by:pdoriley
  • 9
  • 8
  • 5
  • +3
27 Comments
 
LVL 40

Assisted Solution

by:Fatal_Exception
Fatal_Exception earned 140 total points
ID: 12268769
DOS BATCH FILE TUTORIAL

http://www.chebucto.ns.ca/~ak621/DOS/BatBasic.html

Let me make a further suggestion.  Batch files were fine a while ago, but if you really want to learn scripting, try Visual Basic, as this language is much more suited to the Windows Server line, and logon scripts...  MS has some excellent on-line videos (level 100) that will start you off.   By watching these videos, you can also apply for a free VB.NET Standard programming interface..

I will try to find some site for you if you are interested..

FE
0
 
LVL 95

Assisted Solution

by:Lee W, MVP
Lee W, MVP earned 360 total points
ID: 12268956
The tutorial Fatal Exception posted isn't bad, but it is REALLY a beginning tutorial.  The tutorial might explain this itself, but here's my comments:

batch files are simply sequencially executed commands.  Ever drop to a dos prompt and type "copy file1 file2"?  or perhaps "dir"?

You can get information on the various commands included with Windows by typing "help" at a dos prompt in Windows NT/2K/XP.  You can type "help | more" to pause the list as it goes by.  That command will give you a basic idea of what the commands do.  For a more elaboarte explanation and possible examples, take any one of the commands listed and type them with a /? at the end - for example "dir /?"  This tells you all the available options for a directory listing.

Some special commands in DOS:

| (typically the SHIFT-\ character) - this sends the output of the first command into the second command as a parameter.  for Example, if you enter "more boot.ini" the boot.ini file should display itself and pause every 24 lines or so, so that you can read it (if the file is shorter than 24 characters, it just shows the whole file).  By entering "help | more" the file that is "more"'d is the text spit out by help.  This character can be especially useful in pausing screens and finding specific text in a typed file.

& - this command means to execute the next part of the line as a seperate command.  For example, if you want to release and renew your DHCP assigned IP Address, you can execute the following command on ONE line - "ipconfig /release & ipconfig /renew"  I use this concantonation often when I want to restart a service from the command line - it's the fastest possible way to do it, as far as I can tell.

>, >>, <
The > character redirects output to a text file, specified after the > character.  For example: DIR /? > dir.help sends the usage information normally displayed by dir to the file dir.help (creating it if it doesn't exist, overwriting it if it does).  You can then open this file in notepad and see the contents.  The >> tells the command interpreter to APPEND the file instead of overwriting it.  For example executing this command "dir /? > command.help" creates or overwrites the file command.hlp.  Then next executing "rd /? >> command.help" will APPEND the text to then of the command.help file, so that that file has both commands output in it.  The < character redirects INPUT.   I don't use this often and can't actually come up with a reason you'd use it, but it's there and that's what it does.  Further, there are programming concepts of STANDARD ERROR and STANDARD OUTPUT - > works with standard output and is, in fact, the same as saying 1> (for example "dir /? 1> dir.help).  STANDARD ERROR is referred to as 2.  If you try "copy boot.ini boot.bak > copy.log" a file called copy.log is created where the results of that command are stored.  If you tried to copy a nonexistant file "copy ajsfdklja.kkj test.txt > copy.log" then you'd receive an error message the copy.log would be empty.  Do this "copy aajahfdd.kkh test.txt 1>copy.log 2>copy.err" and two files would be created, one for the log of standard output and one for the log of standard error and NOTHING would be displayed on the screen.  Lastly, if you want the standard error and standard out to go to the same file, you'd execute "dir /? > dir.help 2>&1" - this means send standard error (2) to the same file as standard out (&1).

Some VERY useful commands include FOR, IF, and GOTO.  I use them in almost every script.  Be sure to check them out by running FOR /?, IF /?, and GOTO /? at a cmd prompt.

Also, note that this really isn't DOS.  This best called a "Command Interpreter".  DOS doesn't have many of the commands used with Windows NT based scripting.  Indeed, if you open a "DOS" prompt by running "command" at start -> run, then you won't be able to use these features - NT/2000/XP has two popular command interpreters, most people only use cmd.exe, but command.com also exists and is less robust.

Lastly, Check over the MSDOS topic area - most of the questions there are actually on scripts.  Check out the PAQ'd questions and you should see how some things can be done.
0
 
LVL 95

Assisted Solution

by:Lee W, MVP
Lee W, MVP earned 360 total points
ID: 12268976
I don't necessarily disagree with the idea of learning VB instead - it's used in SO MANY different places in Windows and windows apps.  BUT I'm a big fan of using common things that ALL versions of NT based OSs can understand without question.

Echo is a great command if you want to "print" text to the screen that the user can read.  REM is great for commenting on your script - always good to comment so that you know what you were trying to do and why.  (See some of my sample scripts in the MSDOS area, and I'm sure some people will also have done this)

Also, another thing to take note of are your environment variables.  From a command prompt, type "SET" - the list that appears are your default environment variables.  You can add more by using the SET command or the Resource kit utility SETX (run them both with the /? to see more about how they are used).

An example of using environment variables would be:

REM Check the OS environment variable - if os = NT then goto the NT section, else run the 9x section
IF "%os%" == "windows_nt" goto NTSection
:9xSection
REM Do 9x stuff here using 9x versions of the commands
command1
command2
REM We're done with the 9x specific stuff - and NT stuff won't work - so skip the NTSection and goto END
Goto End
:NTSection
REM Do NT stuff here using NT versions of the commands
Command1
command2
:End
0
 

Expert Comment

by:saadat_saeed
ID: 12269761
you could also use vbscripts or jscripts or even kix (www.kixtart.org) scripts as options!
0
 
LVL 40

Expert Comment

by:Fatal_Exception
ID: 12270799
Lee..  nice explanation and tips, my friend..!!

FE
0
 
LVL 14

Expert Comment

by:JohnnyCanuck
ID: 12270880
One thing I've noticed when working with the command prompt is that you have to use the short folder names in the path rather than the long versions.  For example, "xcopy c:\documents and settings\username\my documents\my vacation pics\*.* e:" won't work.  You have to change it to "xcopy c:\docume~1\username\mydocu~1\myvaca~1\*.*".  You can find out the short version by doing a "dir /x".
0
 
LVL 40

Assisted Solution

by:Fatal_Exception
Fatal_Exception earned 140 total points
ID: 12270997
Yes, but the Command Interpreter (cmd.exe) can use the Long File name format, whereas the DOS shell (command.exe) can only use the 8.3 naming convention...  I am sure this is documented somewhere....

Okay, here is the difference between the two:

http://www.computerhope.com/issues/ch000395.htm
0
 
LVL 95

Assisted Solution

by:Lee W, MVP
Lee W, MVP earned 360 total points
ID: 12271212
Thanks FE,

Another thing to note - when using "if" it's good to enclose the variables and text in quotes.  It's not actually required, but here's an example of why you do it:

Windows NT/2K/XP will correctly evaluate this:
   IF %os% == Windows_NT Goto NTStuff
seeing:
   IF Windows_NT == Windows_NT Goto NTStuff

Windows 9x does NOT use the %os% environment variable - it doesn't exist.  As a result, if it attempts to evaluate the same command, it will see:
   IF == Windows_NT Goto NTStuff
This will generate an error (Since %OS% doesn't exist it's effective valule is blank - nothing.  So not seeing the first parameter will cause an error, BUT, if you enclose things in quotes, then the quotes become part of the evaluation:
   IF "" == "Windows_NT" Goto NTStuff
And likewise on Windows NT
   IF "Windows_NT" == "Windows_NT" goto NTStuff

And JohnnyCanuck illustrated my point (and FE provided a good link to an explanation) of why you want to use CMD.EXE instead of COMMAND.COM
0
 
LVL 1

Expert Comment

by:SimonUK
ID: 12272538
I've love to know how to echo a backspace in a batch file - look out for it as a seperate thread because I think it deserves points !

Here's the thrust:

echo Deleting file...
del file.txt
echo Done !

Will give a two line result.  Can I echo a backspace to create a result that would show:

Deleteing file... Done !

WITHOUT a cls and re-echo ?


Simon
0
 
LVL 40

Expert Comment

by:Fatal_Exception
ID: 12272607
Hmm..  I don't believe so in this case, not unless you put it in one line...
0
 
LVL 95

Assisted Solution

by:Lee W, MVP
Lee W, MVP earned 360 total points
ID: 12272651
Another tutorial site (focuses on the capabilities of the Command.com interpreter)
http://www.geocities.com/thestarman3/DOS/DOS7INT.htm

and this one seems quite interesting:
http://www.macalester.edu/~fines/batch_tricks.htm
0
 
LVL 14

Expert Comment

by:JohnnyCanuck
ID: 12272656
Yeesh!  Thanks for the info on cmd.exe.  Why the heck does xp, 2k and nt default to command.com instead?  All this time and I never knew there was a difference - stupid microsoft.   However, I still believe that you must use the 8.3 naming convention when running a batch file.  Unless you can know how to change the default command prompt from command.com to cmd.exe?
0
 
LVL 1

Author Comment

by:pdoriley
ID: 12273333
Thanx, so. uh... how do I write a batch file that clears my cookies when I logon to XP again?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 40

Assisted Solution

by:Fatal_Exception
Fatal_Exception earned 140 total points
ID: 12273391
I suppose, in its simpliest form:

=======Start Copy=========

cd C:\Documents and Settings\%username%\Local Settings\Temporary Internet Files
del *.*

========End Copy==========

Save it as DelCookie.bat and use gpedit.msc to call it at startup as a logon script...  Remember that this will delete all your Temp IE files including all cookies...
0
 
LVL 40

Assisted Solution

by:Fatal_Exception
Fatal_Exception earned 140 total points
ID: 12273426
BTW:  you can use the %username% wildcard as it is..  it will delete the Temp Int Files of the user that logs in...
0
 
LVL 1

Author Comment

by:pdoriley
ID: 12283208
To Fatal Exception, thank you:  I'm new to batch files.  
Do I use the command prompt to do this or should I save this in a notepad?

Then type :
Start copy
cd C:\Documents and Settings\%username%\Local Settings\Temporary Internet Files del *.*  
End copy

Save as DelCookie.bat  ( in save as in notepad? or in DOS - HOW do I save it as this in DOS)?


Finally, How do I use gpedit.msc to call it at startup as a logon script?


Thanks again.


0
 
LVL 95

Expert Comment

by:Lee W, MVP
ID: 12283340
actually, the way windows saves temporary internet files and cookies, that wouldn't work.

Open notepad and put the stuff between the lines below in the text file.  Then save it as "cleanupie.cmd"
-------------------------------------
REM The next two lines change into the current user's profile and
REM delete any temporary internet files remaining in their profile.
cd %userprofile%\local settings\temporary internet files\content.ie5
for /f "tokens=1" %a in ('dir /ad /b') Do cd %a & del *.* /q & cd ..

REM The next two lines remove all the cookies.
cd %userprofile%\cookies
del *.* /q
-------------------------------------
0
 
LVL 40

Expert Comment

by:Fatal_Exception
ID: 12283599
Much nicer, lee...  

Regarding gpedit..  If you are working in a domain, the way to do this is with Group Policy, but if you are in workgroup, then the easy way is to use the Local Users and Groups from Computer Management...  In the properties of the user, you can stipulate a logon script to run..  Here is an MS article on this...:

http://support.microsoft.com/default.aspx?scid=kb;EN-US;315245
0
 
LVL 1

Author Comment

by:pdoriley
ID: 12283784
and now,   do I use the full-style pathname or the short-style pathname.
0
 
LVL 95

Expert Comment

by:Lee W, MVP
ID: 12283816
Thanks, FE.

For my script to work, you must use the cmd.exe command interpreter.  That being the case, long path names SHOULD be fine.  Indeed, when the script is interpreted, it will expand "%userprofile%" to what is most likely "C:\documents and settings\username", so long dir names should be fine.
0
 
LVL 1

Author Comment

by:pdoriley
ID: 12284324
I only understand 50% on what do to.

I am writing my first batch file and I want it to clear my temp + cookies in I.E., every time I logon to Win XP Pro Sp2/

From start to finish guys, what do I do to write, setup, and execute this batch file..   For example, if I have to save it as  DeleteCookie.bat, how do I do that?

The points will go to the best instructions.  THANK YOU.
0
 
LVL 95

Assisted Solution

by:Lee W, MVP
Lee W, MVP earned 360 total points
ID: 12284402
You do realize you can split points among people...

The script I posted earlier - and here:
-------------------------------------
REM The next two lines change into the current user's profile and
REM delete any temporary internet files remaining in their profile.
cd %userprofile%\local settings\temporary internet files\content.ie5
for /f "tokens=1" %a in ('dir /ad /b') Do cd %a & del *.* /q & cd ..

REM The next two lines remove all the cookies.
cd %userprofile%\cookies
del *.* /q
-------------------------------------

That script will erase your cookies and temporary internet files.  Save the lines between the ---- lines to a file, any name you want to give it, but ending in .cmd

Create a shortcut to this script and place it in %userprofile%\start menu\programs\startup

Whenever you log in, that script will execute and clean out the files.

Do you want this script to run for EVERYONE on ONE computer?
Do you want this script to run for EVERYONE on the NETWORK?
Do you want this script to run for JUST YOURSELF (this is what it will do, it can be modified to do everyone on the computer and/or the network).
0
 
LVL 1

Author Comment

by:pdoriley
ID: 12285014
leew, if you show me how to do it with EVERYONE on ONE computer and EVERONE on the NETWORK, I will give you more points!
0
 
LVL 1

Expert Comment

by:SimonUK
ID: 12285020
To add a little to that, if you're REALLY starting from scratch:

Highlight leew's script and copy it into notepad.  Save the file as filename.cmd but when you do this, put it in quotes - ie "filename.cmd" otherwise notepad will add a .txt to the end, which you don't want.
0
 
LVL 40

Expert Comment

by:Fatal_Exception
ID: 12287215
Looks like your questions are answered...  Anything else?
0
 
LVL 95

Accepted Solution

by:
Lee W, MVP earned 360 total points
ID: 12287255
EVERYONE ON ONE COMPUTER:
Instead of placing the script in %userprofile%\start menu\programs\startup, put the script in %allusersprofile%\start menu\programs\startup

EVERYONE ON THE NETWORK:
Instead of placing the script anywhere on a local computer, put the script in the domain controller's NETLOGON share (depends on your domain name, but it should be something like %windir%\sysvol\sysvol\yourdomainname.com\scripts 0 you can look at your shares in computer management on the domain controller to find the exact path).  Put the script there and then set everyone's logon script to this script name.  For example, if you call it cleanie.cmd, then everyone's login script should be equal to cleanie.cmd (if you already use login scripts, just append the script contents I posted to the beginning or end of the script).

ALTERNATELY:
Create a Group Policy Object and set this as a startup script.  This can be easier.  See:
http://64.233.161.104/search?q=cache:ZdjF3E_vOeQJ:www.microsoft.com/windows2000/techinfo/planning/management/groupsteps.asp+Create+Group+Policy+Script+How&hl=en

(The above link is a cached google page - Microsoft seems to have reorganized it off their site)
0
 
LVL 40

Expert Comment

by:Fatal_Exception
ID: 12304846
Thanks...   good luck with your new tools..!!  :)

FE
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

I don't know if many of you have made the great mistake of using the Cisco Thin Client model with the management software VXC. If you have then you are probably more then familiar with the incredibly clunky interface, the numerous work arounds, and …
I use more than 1 computer in my office for various reasons. Multiple keyboards and mice take up more than just extra space, they make working a little more complicated. Using one mouse and keyboard for all of my computers makes life easier. This co…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now