Saturday, September 17, 2011

Useful Script for Network Backup

Here is an interesting backup script from one of our customers. It requires an external tool to be run, but allows to perform backup from many computers over the network:
@echo off
@set dircmd=/b
set folder=Documents and Settings
for /F "tokens=1 usebackq delims==\ " %%i IN (`net view`) DO (
echo Start copying %%i...
start /wait /min /high robocopy.exe "\\%%i\C$" X:\backup\uim\%%i\C *.doc *.xls /S /R:1 /W:120 /XD RECYCLER batmail "Application Data" game* "Default User" "ÿáí½«¡δ" "Local Settings" windows winxp wxp w2k winnt "Program Files" Temp NetHood Recycled Install "The Bat!" "System Volume Information" readme /XF "~*.*" readme /XJ /XO
start /wait /min /high robocopy.exe "\\%%i\D$" X:\backup\uim\%%i\D *.doc *.xls /S /R:0 /W:1 /XD RECYCLER SCANJET batmail "Application Data" game* "Default User" "ÿáí½«¡δ" "Local Settings" Temp Recycled Install readme/XF "~*.*" "System Volume Information" readme /XJ /XO

Wednesday, September 14, 2011

Creating a New User Account via Batch Files

Q: I need to write a batch file that creates a new user account. The account's name and password should be passed as parameters like batch_file name pass. What should I do?

A:
Start Dr.Batcher and type the following script:

@echo off
if "%~2"=="" goto error
if "%~1"=="" goto error
net user %~1 %~2 /add
goto :EOF
:error
echo Usage: %~0 user password

That's all!

Friday, September 9, 2011

Removing Unnecessary Trailing Spaces

Imagine: we have a variable with some string data, and we have to remove unnecessary spaces from the end of this variable. The code below shows how to solve this problem:

@echo off
setlocal
set "a=111 222 "

:loop
set /a n+=1
for /f "tokens=%n%" %%i in ("%a%") do (
if not "%%i"=="" set b=%b%%%i && goto:loop
)

set a=%b:~0,-1%
set b=
echo "%a%"


Of course, you have to change this code a bit before using it. You can do it with the help of our award-winning batch files editor. Hope you'll find this example useful.

Sunday, August 28, 2011

Sorting Web Pages Archive

The task is to sort the archive of different Web documents.

There is a plenty (about 5 thousands) of files named the following way:
number(3-6 digits)_name_.zip(jar,sis)
And the same amount of images in 'Screens' folder:
number(3-6 digits).jpg(gif,png)
Alse there are Web pages in 'Html' folder:
number(3-6 digits).htm(html)
Is it possible to write a batch script that creates folders named after a file and move there a file, a picture and a Web page? ZIP archive should be also extracted there.


The batch script to solve this task looks like this:

@Echo Off
Set ArcDir=c:\archives
Set ScreenDir=c:\screens
Set HTMLDir=c:\html
Set OutDir=C:\
For %%A In (%ArcDir%\*.zip %ArcDir%\*.jar %ArcDir%\*.sys) Do (
md "%%~nA">Nul 2>&1
If /I "%%~xA"==".zip" (
pkzip -extr=up "%%A" "%OutDir%\%%~nA">Nul 2>&1
) Else (
Copy /y "%%A" "%OutDir%\%%~nA">Nul 2>&1
)
Copy /y "%ScreenDir%\%%~nA.*" "%OutDir%\%%~nA">Nul 2>&1
Copy /y "%HTMLDir%\%%~nA.html" "%OutDir%\%%~nA">Nul 2>&1
)

Hope you'll find this example useful. You can modify this script with the help of our batch files editor called Dr.Batcher.

Wednesday, August 24, 2011

Installing Many Programs at Once

It takes a lot of time to install different software on the users' workstations. It is much easier to run a single batch script created with the award-winning batch files editor and install all these programs immediately. The script will look like this one:
@echo off
start /wait "" "C:\Install\setup1.exe"
start /wait "" "C:\Install\setup2.exe"
start /wait "" "C:\Install\setup3.exe"
start /wait "" "C:\Install\setup4.exe"
start /wait "" "C:\Install\setup5.exe"
It is not hard to change the paths to the installation EXEs and their names. But to simplify the installation process you should search for command-line parameters of popular installation engines (InnoSetup, NSIS, Windows Installer etc.). These parameters should let you install software in 'silent' mode and specify destination folder, components to be installed and other settings.

Sunday, August 21, 2011

Retrieving the List of Files Modified Lately

It's quite a common task to retrieve the list of files modified during the latest few days. It is easy to solve this task with the help of batch files:
@echo off
for %%i in (bmp jpg png gif) do (
forfiles -pC:\Test -s -m*.%%i -d+14 -c"cmd /c echo @PATH @FILE"
)
As far as you can see, this batch file searches for images in 'C:\Temp' folder, and shows those of them that were modified during the latest two weeks.
Hope you'll find this small example useful.

Monday, August 15, 2011

Clearing Sub-Folders in the Given Folder

Imagine: you have a shared folder where users can create there own sub-folders. Sometimes it is necessary to clean the whole shared folder, but the cleaning batch script has to leave all the sub-folders and just delete everything inside them. How to perform it? The small script below shows you quite an easy way to solve this problem. Hope you'll find it useful.
@echo off
pushd "U:\Share Folder"
for /d %%i in (*) do (
pushd "%%i"
rd /s /q "." 2>nul
popd
)
popd

Wednesday, August 10, 2011

Removing Unnecessary Dots and Slashes from Date

When you want to use the current date as a part of a file's name, you want to see something like '01012011'. Usual 'date' variable gives you human-readable date with additional dots looking like this: '01.01.2011'. Or something like this: '01/01/2011'. It depends on the settings of your copy of Windows. Fortunately, it is not hard to remove unnecessary characters from the string with the date. All you need to do is to use the following construction:
echo %date:.=%
This code will remove dots from the string with the current date. Can you consider the string that allows you to remove slashes?..

Monday, August 8, 2011

Search for a File on Local Drives

We all need sometimes to find a certain file on a local disk drive. It is not hard to implement search by name with the help of batch files. But what to do if you need to search for a file on all the drives available on a computer? The example script below shows how to perform it.
@echo off
setlocal
for %%i in (c d e f g h i j k l m n o p q r s t u v w x y z) do (
for /f "tokens=*" %%a in ('dir /b /s /a-d %%i:\FileName.ext 2^>nul') do (
set "foundFile=%%a" & goto found
))
echo File not found
goto :EOF
:found
echo File found - %foundFile%

As far as you can see, we simply look through all letters for logical drives and then search for the needful file on the each drive separately.

Thursday, July 14, 2011

Copy Files and Automatically Rename Existing Ones

Usually while copying large amount of files it is necessary to rename the existing files to avoid overwriting them with the copied ones. Usual commands like copy or xcopy don't let you perform renaming in automatic mode. Still you are able to create a batch script that will help you to solve this problem:
@echo off
for %%i in (SourceDir\*) do (
if exist "DestDir\%%~nxi" (
mv "%%i" "DestDir\~%%~nxi"
) else (
mv "%%i" "DestDir"
)
)

You can change this example script according to your needs with the help of our batch files editor. Hope you'll find this small example useful.

Saturday, July 9, 2011

Script for 'Remote Execution' of Programs

It is useful sometimes to download a program from a remote server and run on the computer where the batch script is running. It is not so hard to implement it:
title Loading program... Please wait...
@echo off
net use w: \\192.168.x.x\a1 > nul
echo "1. Disk connected"
cd d:\
d:
md 123
cd d:\123
md Program
copy w:\Prg.exe d:\123\Program\Prog.exe > nul
echo "2. File updated"
start d:\123\Program\Prog.exe > nul
echo "3. Run programm"
net use w: /delete > nul
echo "4. Disk disconnected"
exit

You can change this batch file with help of our award-winning batch files editor. Hope you'll find this example useful.

Thursday, June 23, 2011

Batch File to Create Virtual Disk Drive

Here is the small batch file that lets you create virtual disk drive. This drive doesn't really exist on your computer, it's something like a shortcut to the certain folder on your computer's HDD. The script will look like this:
net use X: \\komp\updat pass /user:user /persistent:yes >Nul 2<&1
set dir=T:\home
set od=X:\
del /Q /F %dir%\*.*
PING 1.1.1.1 -n 1 -w 2000 2>NUL | FIND "TTL=" >NUL
copy /Y %od%\*.* %dir%
As far as you can see, first of all we check for existence of a virtual drive with the physical letter. If this drive doesn't exist, we create it. Finally we copy some files on it.

Tuesday, June 21, 2011

Retrieving Path to the Start-Up Folder

Sometimes you need to place something in Windows start-up folder. Well, it is not hard to do it, but first of all you need to know where this folder is situated. Fortunately, it's not hard, either. Here is the script that lets you retrieve path to the start-up folder:
for /f "tokens=2*" %%i in ('reg query "hkcu\software\microsoft\windows\currentversion\explorer\shell folders" /v ;Startup ^|find /i "startup"') do @set "startfolder=%%j"
echo %startfolder%
You can use this example to create scripts with the help of our powerful batch files editor. Hope you'll find this post useful.

Monday, June 13, 2011

Passing the Current Date to XCOPY

XCOPY is a really useful console command that allows you to make copies of files in a fast and easy way. One of the parameters of this command is '/d':

/d[:mm-dd-yyyy] : Copies source files changed on or after the specified date only. If you do not include a mm-dd-yyyy value, xcopy copies all Source files that are newer than existing Destination files. This command-line option allows you to update files that have changed.

If you need to pass the current date to this command, you'll be surprised: on some configurations of the operating system %date% returns the current date in dd.mm.yyy format, while XCOPY requires mm-dd-yyyy. What to do? Here is some batch code that helps you to solve this problem:

@echo off
setlocal
set "dd=%date:~0,2%"
set "mm=%date:~3,2%"
set "yy=%date:~-2%"
xcopy c:\*.txt c:\temp /d:%mm%-%dd%-%yy%

You can use this code in your batch files that can be written with the help of our award-winning batch files editor. Hope you'll find this information useful.

Friday, June 10, 2011

Batch File to Check Internet Connection

It's useful to create a small batch file that will check your internet connection and restart the computer if there is no connection at the moment. Of course, nobody restricts you to reset the connection parameters or perform any other actions instead of rebooting the computer. You can take the example below and modify it with help of our award-winning batch files editor.
So here is the script to solve the problem described above:
@echo off
ping m-w-c-s.com

if errorlevel 1 shutdown -r -f -t 0
exit
As far as you can see, the way to check the connection is really simple: we just ping Mental Works Computing Software's site and reboot if it is not available. You can use Google or Yahoo! instead if you prefer.

Saturday, June 4, 2011

Moving a File One Level Upper

We were asked via e-mail about moving files one level upper. Suppose this short example will be useful for everyone:
MOVE 1.ext ..\1.ext
Of course, the file to be moved and the batch script have to be placed in the same folder.

Sunday, May 29, 2011

How to Start a Batch Script in Background Mode

It is sometimes useful to run batch scripts in a background mode without showing users the console window with the script's input and output. There are dozens of service scripts that perform some tasks while the user is working with its usual software. But there is a problem to start all these scripts in a background mode.
Let us remind that our award-winning batch files editor Dr.Batcher lets you compile a batch file to Windows executable (EXE). While compiling you can choose option to run the output EXE in invisible mode, i.e. without showing any windows at all. You can also include all necessary external files like 3rd-party console programs or additional scripts. The compiled executable file can be run on any Windows PC or laptop without any additional software installing.
So don't forget that Dr.Batcher lets you compile your batch scripts into Windows executables!

Tuesday, May 24, 2011

Deleting a Registry Branch at the Given Time

How to delete certain branch in system registry with the help of batch files? The task seems to be quite difficult, but fortunately it is not so hard to implement it. All you actually need to perform this operation is the single line of batch code:
at 00:36 reg delete HKLM\Software\MyPrg /f
Don't forget to change the time and registry branch before using this solution. You can use our award-winning batch file editor to change this small script in according to your needs.

Sunday, May 22, 2011

Generating a Sequence of Random Numbers in Batch Files

It's sometimes necessary to generate a sequence of random numbers in a script. In this blog you can find some posts on dealing with random numbers, still this question has never been discussed. Here is an example that shows how to generate and print on the console 99 random numbers. You can use our award-winning batch file editor to redirect the output to a text file and then build a plot in Excel to check these numbers being really random.
@echo off
setlocal
for /l %%i in (0,1,99) do call:rand %%i
for /f "tokens=3 delims=_=" %%i in ('set rand_') do echo %%i
goto:eof
:rand
set rand_%random%%random%=%1
This example can be useful for generating random data for different testing purposes. Hope you'll enjoy it.

Friday, May 20, 2011

Useful Update for the Previous Blog Post

After publishing the previous blog post, we have received a message with the script that lets one avoid printing all the details of pinging many IP addresses and saying which of them are available instead. It is really a handy and useful script and we decided to share it with the readers of our blog.
@echo off
for /l %%i in (1,1,255) do (
ping -n 1 192.168.1.%%i | findstr "TTL=" 1>nul && (
echo 192.168.1.%%i is UP
) || (
echo 192.168.1.%%i is DOWN
)
)

Tuesday, May 17, 2011

Another Way to Ping Many IPs at Once

We have already discussed how to ping the given list of IP addresses. Now let's look what we can do if this list isn't placed in a text file. As usual, the solution is very simple:
for /L %%i in (1, 1, 255) do ping 192.168.1.%%i
Of course, you have to use your own subnet mask instead of 192.168.1 in the example above. Hope this small script will help you to write your own powerful batch files.

Sunday, May 15, 2011

Checking File Size in Batch Files

It's sometimes necessary to check the size of a given file. For example, if you are to delete too big files on your hard drive or split single file into many parts. As usual, batch files are powerful enough to perform such task. The example below shows how to check batch file size (file is called 1.txt) and exit the script if the size is equal to 100 Kb.
for %%a in (1.txt) do if %%~za EQU 102400 goto :EOF
You can use this example in scripts that you create with help of our award-winning program designed to write batch files.

Friday, May 13, 2011

A Small Quiz Script :)

There are lots of useful scripts already published on this blog. You can create even more of them with the help of Dr.Batcher. Now it's time for jokes. Let us introduce a small quiz script that can be useful to check whether you are lucky today. Hope you'll enjoy it:)
@echo off
set i=0
echo Thinking of a number...
:rand
set nmb=%random%
if %
nmb% GTR 10 goto rand
if %
nmb% EQU 0 goto rand
echo Now you can try 3 times to guess the right one!
:enter
set /p "ent=Your number : "
set /a i=%i%+1
if %ent% EQU %
nmb% (
echo You're lucky!
pause
exit
)
if %i% LSS 3 (
goto enter
)
if %i% EQU 3 (
echo Game Over:(
pause
)

Sunday, May 8, 2011

Search for Running Process and Start It if It Is not Found

It is quite a common task to start some processes in an automatic way. Of course we usually have no need to run many instances of the application simultaneously, thus we have to check running processes first. Fortunately, batch files are pretty useful in this case and let us solve the problem in a fast and simple way. The solution will look like:
tasklist | findstr /i yourapp.exe 1>nul || start "" "C:\Program Files\Megacorp Inc\yourapp.exe"
You can easily modify this single-line script with the help of our award-winning batch file editor or send your questions and suggestions to us.

Sunday, May 1, 2011

Random Numbers Generator

As far as you probably know it is not so hard to generate random numbers with the help of batch files. But if you want to make sure that your number is unique among the given sequence of numbers, the task becomes a little bit more complicated. Here is a quite simple solution that can be modified with the help of our powerful batch files editor:


@echo off
setlocal
:try
set "rand=%random%%random%"
if "%rand:~6%"=="" goto try
1>nul 2>&1 type prevrand.txt | find "%rand:~0,6%"
if not errorlevel 1 goto try
echo %rand:~0,6%>prevrand.txt




As far as you can see, we use a special text file to store all previously used numbers. Of course, it's better to remove it after you have done all the work, whatever you need to do with the generated numbers. Hope you'll find this small random numbers generator useful.

Tuesday, April 26, 2011

Another Example with Renaming Files

Renaming files is likely the most common task being automated with the help of batch files. Here we will discuss how to add the date of file's creation to its name. As far as you can see, the script to automate this task is quite simple, but you can enhance it with the help of our powerful batch files editor.
SETLOCAL ENABLEDELAYEDEXPANSION
@echo off
for /f %%i in ('dir /b') do (
set aaa=%time%
set a1=!aaa:~0,2!
set a2=!aaa:~3,2!
set a3=!aaa:~6,2!
ren "%%i" "!a1!-!a2!-!a3!_%%i"
)
endlocal
If you run this script, you will see that it adds the date before the name of the file. It is not hard to modify the script to make it add the date to the end of batch file.
And here is also another version of this task's automation:
@echo off
for /f %%i in ('dir /b') do (
set "file=%%i"
call :ert
)
goto :eof
:ert
ren "%file%" "%time:~0,2%-%time:~3,2%-%time:~6,2%_%file%"
Both of these scripts are quite quick, so in general you can use any of them.

Saturday, April 23, 2011

How to Remove Numbers from Filenames

Let's discuss another simple task that can be automated with help of batch files. The task is to remove numbers from filenames like these:
name[1].ext
name[2].ext
name[3].ext
name[4].ext
name[5].ext
...
So what do you have to do? You can use a simple script like this:
@echo off for /f "tokens=1,2,3 delims=[]" %%a in ('dir /b *[1].*') do ren %%a[%%b]%%c %%a%%c
Hope you'll find it useful.

Wednesday, April 20, 2011

Copying Strings from One File to Another

The task to be discussed in this post looks very simple: copy some strings from a text file to another one. The file and the amount of strings are given. Here you can see the solution:
@echo off
setlocal enabledelayedexpansion
set "N=17"
set "count=0"
for /f "tokens=*" %%a in (first_file.txt) do (
if !count! GEQ !N! goto :EOF
echo %%a>>second_file.txt
set /a "count+=1"
)

But you can also try another version of this script. It will look like this (you should declare variables to run this script):
set count=0
for /f "skip=2 tokens=*" %%a in (%file_name%) do (
set /a count=!count!+1
if /i !count! leq N echo %%a>>new.txt
)
Hope you'll find these scripts useful.

Tuesday, April 19, 2011

Dr.Batcher 2.1.5 is Released

We are glad to introduce the new version of our award-winning software to create batch files. In this version added French translation, support for checking used bookmarks on toolbar, small bugfixes.
Click here to download it right now. Hope you'll enjoy our work.

Sunday, April 17, 2011

How to Answer Y/N to Console Program from Batch File


Sometimes it is necessary to answer 'Y' or 'N' to a console program during the execution of a batch file. If your file is running under a user's sight, it causes no problems, but if you need to run it in a completely autonomous mode, you have to find a solution.
The solution is really simple: you should just write 'echo Y | ' in your batch file, where the name of a program that wants to know your decision is. Sometimes you should type 'YES' or 'NO' instead of short forms of 'Y' and 'N'. So read carefully the program's manual before passing answers to it.

Friday, April 15, 2011

How to Turn Off Screen Output in Console

Not long ago we received a letter with the following question:
How to make a command not to type anything while its execution? I tried CLS but it makes nothing...
Though our award-winning batch files editor Dr.Batcher allows you to create scripts very easy, it still doesn't let you just check a box to turn screen output off (we'll implement this feature one day, we promise). So you should use the following instruction:
ping 127.0.0.1 > nul
Of course, you can use any command you like, not only 'ping'. The main trick is '> nul'. It redirects the output from console to... nowhere! So you won't see anything except the command's name and given parameters themselves.

Tuesday, March 29, 2011

Adding Quotes to Lines in Text

Let's discuss quite a simple task today. Imagine: you need to change each line in a text file by adding quotes to it. I mean you want to get from list like listitem1, listitem2, listitem3... list like "listitem1", "listitem2", "listitem3". This is quite a simple task, and the script solution looks like this:
@echo off
for /f "usebackq tokens=*" %%c in ("about.txt") do (
echo "%%c",>> about1.txt
)

As far as you can see, it's not difficult to write this script with help of our award-winning batch files editor. Hope you'll find this small example useful.

Friday, March 25, 2011

How to Register Many DLLs/OCXs at Once

It is sometimes necessary to register a COM or ActiveX library. As far as you know, it is easy to perform it with help of Regsvr32 utility by Microsoft. But it is hard to type the name of library to be registered each time when you need to register a lot of them. It's really easier to copy all needful files to a single folder and then register them all with help of really simple script:
for %%i in (c:\DLL\ActiveX\*.dll) do regsvr32 %%i
for %%i in (c:\DLL\ActiveX\*.ocx) do regsvr32 %%i
Please note that you can register even remote files
for %%i in (\\192.168.102.184\DLL\*.dll) do regsvr32 %%i
for %%i in (\\192.168.102.184\DLL\*.ocx) do regsvr32 %%i
Hope you'll find this example useful.

Wednesday, March 23, 2011

Dr.Batcher 2.1.4 Is Released

We are glad to introduce an update for our award-winning batch files editor. In this version you will find the following new features:
  • tab-bar with bookmarks in professional mode;
  • support for declining use of unnecessary list parameters in simple mode;
  • support for viewing latest post from 'World of Batch Files' blog on start;
  • 10 new examples;
  • improved compatibility with Windows 7 64-bit;
  • lots of bugfixes.
Hope you'll enjoy this update.

Friday, March 18, 2011

Hiding Password Input in Batch Files

It is sometimes necessary to ask user a password from a batch script. Unfortunately, batch files don't allow you to hide input with "*"s, like ordinary password forms in Windows or Web. Of course, the easiest way is to leave everything as it is, but much better is to hide the password without showing anything. The following batch script shows you how to perform such hiding of characters:
@echo off
echo hP1X500P[PZBBBfh#b##fXf-V@`$fPf]f3/f1/5++u5>in.com
set /p password=Enter password:
for /f "tokens=*" %%i in ('in.com') do set "password=%%i"
del in.com
echo.
echo The Password is:"%password%"
You can easily change this batch file with help of our award-winning tool Dr.Batcher. Hope you'll find both of them (script and tool) useful.

Monday, March 14, 2011

Ping List of IPs

It's pretty easy to ping a single IP with help of standard 'ping' command. But sometimes it's necessary to ping several addresses at once. Unfortunately, ping's syntax doesn't allow you passing the prepared text file as an input parameter to check all IPs listed in it. What to do? Just download Dr.Batcher and start writing really useful script in it.
The script is quite simple. If looks like this:
@echo off
for /f %%i in (test.txt) do ping -n 1 %%i
You can easily enhance it with writing the results of pinging to the text file (log). Input TXT file (test.txt here) should just contain the list of addresses to be pinged, one per line.

Tuesday, March 8, 2011

How to Avoid Using Gotos

Batch files make you to use 'goto', an obsolete and quite unpleasant construction that makes your code unreadable. This is a common opinion, but I want to discuss the way to avoid 'goto' commands in your batch scripts.
The traditional way to build batch files since the early days of MS-DOS looks like this:
if condition goto :THEN
rem Something like ‘else’
rem ...
goto IF_END
:THEN
rem Something like ‘then’
rem ...
:IF_END
This is really different from the way of writing 'if' statements in C, Pascal, Java and even VBScript. Look at the modern batch script below. Does it look like C or Java code?
if
condition (
rem ‘then’
rem ...
) else (
rem ‘else’
rem ...
)

It's not hard to use these constructions, simply don't forget to add 'setlocal enabledelayedexpansion' (without commas).

Friday, March 4, 2011

Batch File to Open URL

Today I am glad to introduce this short post that should give the answer to a short user's question. The question was "How to open URL via batch file?".
Fortunately, to open URL with the default system browser, you should do almost nothing. The sequence of action looks like this:
1) Start Dr.Batcher and create a new batch script;
2) Switch to Simple mode;
3) Add a new command named "Start a Separate Command Promt" (START);
4) Change the value of parameter 'Command or program to start" to your URL surrounded with commas (for example, "http://www.drbatcher.com");
5) Set other needful parameters;
6) Add more URLs if necessary;
7) Enjoy!

Wednesday, March 2, 2011

Remove All Files Except Today's One with Help of Batch Files


Task to be discussed today is "How to remove all files from the specified folder except the file with today's name?". This is not a very common task, but it is useful for making different backup batch scripts. And this task is simple, as far as you can see. The code below shows how to delete all files in the current folder except the file which name contains today's date.
@echo off
attrib +r *%date%*
del /q *.* 1>nul 2>&1
attrib -r *%date%*
Hope you'll find this simple code useful.

Thursday, February 24, 2011

Remove Trash Files with Help of Batch Scripts

We have already discussed some aspects of removing system trash with help of batch files. Still that batch script was not able to remove all system trash by a single mouse click. Script below improves this inconvenience and allows you to remove all system trash under Windows XP. You can easily change it according to your needs with the help of our batch files editor.
if exist c: call :RSVI c
if exist d: call :RSVI d
if exist x: call :RSVI x
if exist y: call :RSVI y
if exist z: call :RSVI z
goto :main
:RSVI
rem Clear Recycler & System Volume Information
if exist %~1:\RECYCLER rd /s /q %~1:\RECYCLER
if exist "%~1:\System Volume Information" (
echo Y|cacls "%~1:\System Volume Information" /T /P "All":F /C
rd /s /q "%~1:\System Volume Information")
goto END
:main
@set dircmd=/b
@del /f /s /q %TMP%\ >nul
@del /f /s /q %TEMP%\ >nul
@for /D %%f in ("%TMP%\*") do rd /q /s %%f >nul
@for /D %%f in ("%TEMP%\*") do rd /q /s %%f >nul
set folder=C:\Documents and Settings\
for /F "DELIMS=" %%f in ('dir "%folder%"') do (
echo ======================= "%%f" ======================== >> c:\deltemp.log
call :EXIST_SUB "%%f"
)
goto END
:EXIST_SUB
@if exist "%folder%%~1\Local Settings\Temp" call :RM_SUB "%folder%%~1\Local Settings\Temp" >nul
@if exist "%folder%%~1\Local Settings\History" call :RM_SUB "%folder%%~1\Local Settings\History" >nul
@if exist "%folder%%~1\Local Settings\Temporary Internet Files" call :RM_SUB "%folder%%~1\Local Settings\Temporary Internet Files" >nul
@if exist "%folder%%~1\NetHood" call :RM_SUB "%folder%%~1\NetHood" >nul
@if exist "%folder%%~1\PrintHood" call :RM_SUB "%folder%%~1\PrintHood" >nul
@if exist "%folder%%~1\Recent" call :RM_SUB "%folder%%~1\Recent" >nul
@if exist "%folder%%~1\Cookies" call :RM_SUB "%folder%%~1\Cookies" >nul
goto END
:RM_SUB
if "%~1" == "" (
echo Usage: DelFolder.cmd FolderName
pause
goto :end
)
for /F %%f in ('dir /A: "%~1"') do (
attrib -R -S -H "%~1\%%f" /D /S
)
echo "Deleting all files from %~1\"
echo "Deleting all files from %~1\" >> c:\deltemp.log
@del /f /s /q "%~1\*.*" >nul
@for /D %%d in ("%~1\*") do (
rem echo "z1:" %%d
attrib -R -S -H "%%d\*.*" /D /S
echo "Deleting folder %%d"
echo "Deleting folder %%d" >> c:\deltemp.log
rmdir /s /q "%%d" >nul
)
:END

Tuesday, February 22, 2011

Using Variables Inside Loops

There are two really useful constructions in batch files: conditions (IFs) and loops (FORs). Both of theme are extremely widely used, and both of them have some difficulties for beginners. Here we are going to discuss one of these difficulties concerning loops.
The difficulty is called 'local variables'. As far as you know, to retrieve the value of certain variable, you have to use the following construction: %variable_name%. But if you use your variable inside a loop, and its value is being changed on each iteration, you should not use this way to access the variable. Try to place %variable_name% inside a loop, and you will retrieve the same value every time. Thus you have to use setlocal enabledelayedexpansion and write !variable_name! instead (don't forget to use endlocal after a loop).
It is not very hard to follow this small tip, just don't forget to use it while you write batch files.

Thursday, February 17, 2011

Batch Calculator

Here is a small example of 'Set' command usage. The script below is a calculator, and as far as you can see we do almost nothing to calculate anything - just take the user's input data and send it to 'set' command that makes all calculations. Of course, this example is not a serious calculator, but it shows a very useful way to make some operations in batch scripts. You can easily include this code into batch files that you create with the help of our powerful batch files editor Dr.Batcher.
@ echo off
:begin
Cls
Title Calculator
Color 71
Echo Enter the expression:
Set /P exp=
Set /A result=%exp%
Echo Your expression: %exp%
Echo Result: %result%
Pause>nul
goto begin

Sunday, February 13, 2011

Retrieving Drive Letters through Batch Files

The task to be discussed today is retrieving already occupied drive letters in Windows. Of course, through batch scripting. This batch file is quite small and simple, and after its execution you can see all the letters on the screen. Of course, you can easily change this batch file.

@echo off
setlocal enabledelayedexpansion
echo list volume>"%temp%\ds.txt"
for /f "skip=8 tokens=3" %%a in ('diskpart /s "%temp%\ds.txt"') do set "used=!used! %%a"
del /q "%temp%\ds.txt" 2>nul
echo The used letters are - %used:~1%

Hope this batch file will be really useful for you.

Friday, February 11, 2011

Merging Sources with Help of Batch Scripting

Batch files are exteremely useful for programmers. Developers can use batch scripting to automate boring jobs like making builds and packaging software. And not only for this - for example, to merge the existing dozens of script files to the single one. Here is the example of script that will help you to merge many JavaScript files placed in the same folder into the single script file. You can easily change this script with the help of Dr.Batcher, an advanced batch files editor.
@echo off
SET NewFile=cpfunct.js
cd \cpfunct\
@echo.>%NewFile%
for %%i in (*.js) do COPY /B %NewFile%+%%i %NewFile%
move %NewFile% ..\%NewFile%

It is useful to store the current version of the resulting JS in top of the file. Here is code that automatically reads and increments the version of the script before merging all files:

@echo off
setlocal
set /p vers=
for /f "tokens=2 delims==" %%i in ("%vers%") do set /a ver=%%i+1
1>main.tmp (
echo var vers=%ver%
more +1 result.js
)
del result.js
for %%i in (*.js) do copy /b main.tmp+%%i main.tmp
ren main.tmp result.js

Have any ideas about further enhancements? Don't hesitate to post your comments or send your suggestions to us!

Wednesday, February 9, 2011

How To Print a Line without Closing CR\LF in Batch Files

'Echo' is likely the most often used command in the whole batch scripting. The only disadvantage of this command is ending CR\LF that is always being put after the text. Unfortunately, there is no command that can print text without closing CR\LF in the standard set of commands provided by MS. Thus we have to write quite a large amount of code to implement this feature.
Here is the code:

@ECHO OFF
> #.SCR ECHO N _CHO.COM
>>#.SCR ECHO E 0100 BB 80 00 43 80 3F 0D 75 FA C6 07 24 B4 09 BA 82
>>#.SCR ECHO E 0110 00 39 DA 7F 02 CD 21 B4 4C CD 21
>>#.SCR ECHO RCX
>>#.SCR ECHO 001B
>>#.SCR ECHO W
>>#.SCR ECHO Q
>>#.SCR ECHO.
DEBUG<#.SCR>NUL
DEL #.SCR
_CHO %DATE% >TEST.TXT
_CHO TEST FIRST WORD >>TEST.TXT
_CHO TEST SECOND WORD >>TEST.TXT

As far as you can see, this code produces a small COM file that is able to print text without closing CR\LFs. Of course, you can easily edit the batch script and rename this COM file from _CHO to any name you prefer. Hope you'll find this post useful.

Saturday, February 5, 2011

Enumeration in Batch Files

It's sometimes necessary to enumerate numbers with help of batch files. It may be needful for counting and renaming files, for adding the numbers to lines of different lists in text files, and for dozens of other different purposes. Here is a small script that will help you to enumerate anything you want. Of course, it is not hard to modify this script with help of Dr.Batcher and apply it to your tasks.
for /l %%a in (1,1,999) do (
set n=%%a
call:ch
)
goto:eof
:ch
set "n=000%n%"
set "n=%n:~-3%"
@echo %n%>>1.txt
This script produces 3-characters numbers (i.e. 001, 002, ..., 999) and writes it down to 1.txt. Hope you'll find it useful for some of your batch files.

Thursday, February 3, 2011

Retrieving Random String from Batch File

The task to be discussed in this post is retrieving a random string from the given text file and then printing it on the screen. When is it useful? For example, you can create the list of user's addresses and send someone a message via 'net send' command as a simple joke. Or even automate the creation of SEO texts with the help of batch files. Enjoy the code:
@echo off
setlocal
set "lines=0"
for /f "tokens=*" %%a in (items.txt) do set /a "lines+=1"
set /a "skip=%random% %% lines"
if %skip% lss 1 (set "skip=") else (set "skip=skip=%skip%")
for /f "%skip% tokens=*" %%a in (items.txt) do set "item=%%a"&goto display
:display
echo %item%
Hope it'll be useful, or at least just amazing for you.

Tuesday, February 1, 2011

How to Sort Out Files of Differnet Types with Help of Batch Files, Chapter II: Sorting Text Files by Their Contents

We have already discussed the question of sorting files of different types with help of batch scripts. But what's about sorting text files by their contents? This task is also quite simple and can be done in a few lines of code. Of course, it becomes even simpler if you use Dr.Batcher to create batch scripts.
So here is the example that can be used in sorting LOGs of different applications or downloaded files, or in other suitable cases. The script searches for the given phrase in all text files placed in the current folder, and if the phrase is found, the file that contains it is replaced to the specified folder.
@echo off
for %%i in (*.txt) do (
find "first phrase" "%%i" > nul && MOVE "%%i" 1
find "second phrase" "%%i" > nul && MOVE "%%i" 2
rem Add here your phrases.
)
Hope this script will be useful for you.

Thursday, January 27, 2011

How to Export Registry Keys Through Batch File

Long time ago I wrote a post on having a deal with Windows registry in batch files. It's time to return to this topic and share a small, but still very useful batch file that will help you to export registry keys to a REG file. This code is really simple, still you can include it into complex script that you create with help of our powerful batch files editor.
Here is the code of this batch file:
@echo off regedit /ea %Temp%\ChkReg.txt "HKEY_CURRENT_USER\Software\MyPrg-1" if exist %Temp%\ChkReg.txt type %Temp%\ChkReg.txt>reg.reg regedit /ea %Temp%\ChkReg.txt "HKEY_LOCAL_MACHINE\Software\MyPrg-1" if exist %Temp%\ChkReg.txt findstr /v /b /i "REGEDIT4" %Temp%\ChkReg.txt>>reg.reg if exist %Temp%\ChkReg.txt del %Temp%\ChkReg.txt
As far as you can see, first of all we export the necessary keys to ChkReg.txt, than copying data itself to REG file, and then remove the temporary TXT. Hope this script will be useful for you.

Tuesday, January 25, 2011

Batch File to Retrieve Batch Files from Network Drive and Pack Them


Here is a useful script that administrators can use to retrieve automatically files from the network drive and pack them immediately after that. All the actions are being logged to the LOG file called by default 1.log. You can easily modify this script with help of Dr.Batcher, a powerful utility designed to create and modify batch files.
@echo Starting>> 1.log
@Echo off
@DATE /t >> 1.log
@TIME /T >> 1.log
@echo Copying and logging results ...
@xcopy v:\post\*.doc /z /c /Q >> 1.log
@echo Packing... >> 1.log
@rar a -ag + YYYY:MM:DD:HH:MM \*.doc >> 1.log
@echo Moving the archive to TEMP folder... >> 1.log
@move *.rar TEMP
@echo Removing DOC... >> 1.log
@del /F d:\*.doc
@echo Done... >> 1.log
Have any suggestions on this batch file? Leave your comments!

Saturday, January 22, 2011

Batch File To Restart Explorer And Reopen Windows

Though this is not a very common task, I suppose this example of batch scripting is still very useful for advanced users of batch files. You can change anything you want in a couple of minutes, especially with help of our powerful and handy batch files editor.
Here is the code to restart Windows Explorer and reopen all windows of the running applications:
@echo off setlocal enabledelayedexpansion for /f "usebackq tokens=8*" %%a in (`"cmdow /t /f | find /i "explorer""`) do ( if /i "%%a"=="explorer" set "open_windows=!open_windows! "%%b"" ) taskkill /f /im explorer.exe>nul start explorer for %%a in (%open_windows%) do ( if /i %%a=="My Computer" (start /min explorer shell:DriveFolder) else ( start /min explorer %%a) )
Hope you'll find this code useful.

Wednesday, January 19, 2011

Detecting the Insertion of USB Flash in Batch Files

How to detect that user inserts USB Flash drive and make computer shut down after this? Here you can see step-by-step explanation.
1. Download and install Dr.Batcher, the program designed to create and edit batch files.
2. Start Dr.Batcher and create new empty batch script (File->New->Empty Batch Script).
3. Add command named "Display a message" (Command->Add), click OK in the "Add Command" dialog.
4. Choose "off" as the first parameter and click "OK".
5. Add command named "Set Label".
6. Set loop as a label name, click "OK".
7. Add command named "If (Condition)". Choose "Edit the condition" in the appeared dialog.
8. Choose "File Exists (Condition Only)". 9. Set the letter of the flash drive as the parameter in the following dialog. Note: "\." after the drive letter should not be removed.
9. Add command named "Go to a Label".
10. Set loop as the label name. Click "OK".
11. Following the instructions in paragraphs 5 and 6, add a label with name end.
12. Add command named "Shut Down or Restart Computer".
13. Set the first parameter of this command equal to -r to restart or -s to shut down
14. To make this file start automatically when you log on, place it inside the "Startup" folder in Start menu.
15. Enjoy!

Monday, January 17, 2011

What Does Bring Dr.Batcher 2.1.3?

We are glad to introduce Dr.Batcher 2.1.3. This version fixes a lot of issues reported by the users of 32-bit version of Windows 7, in the following version we are going to fix issues with running Dr.Batcher under 64-bit Winfows 7. What else will you find in this version? Here is the complete list of new features:
  • new options for changing the way of starting Dr.Batcher;
  • support for storing spaces between command name and its parameters;
  • tabbed "Common Options" dialog;
  • improved compatibility with 32-bit Windows 7;
  • small bugfixes.
Here are some screenshots of the new Common Options dialog:




Hope you'll enjoy our work. Please remember that you are always welcome with your reports and suggestions.

Translate