Showing posts with label techniques. Show all posts
Showing posts with label techniques. Show all posts

Tuesday, August 6, 2013

Using Quotes in Batch Files

It is likely that using quotes is a hard topic for everyone who strats learning batch programming. We'll try to clarify this question a bit.
Quotes is just the way to pass the parameters containing spaces. Let's see an example:
DIR c:\Program Files
It seems that it's all right, and we'll list files and folders from Program Files directory. But this is wrong opinion because the space in batch files is delimiter for parameters passing to the batch command.To pass the single argument to the DIR command you should quote it:
DIR "c:\Program Files"
Quotes is not the part of the folder name. They only let the command know that space is the part of this name.
We kindly remind that Dr.Batcher is the best program to create batch file, both .BAT and .CMD, try it if haven't tried it yet. 

Wednesday, July 17, 2013

Why to Use Variables in Batch Files?

When you write your own batch file, you usually have no need to use  many variables in your code. Batch files with all their GOTOs and old syntax make you hard-code all needful data directly into the batch file instead of trying to make your code a bit flexible. Is this a good practice? We suppose it isn't.
Once written, code with variables can be easily copied to many different new batch scripts. Any you have no need to waste time trying to understandd your old code. Using variables makes your code much more readable and reusable, and this is the main advantage of using them.
The most useful tip is to use system variables instead of hard-coding different Windows folders. For example, it's better to use %SystemRoot% instead of writing directly "c:\Windows". You can watch all system variables by running SET command without any parameters. You can also see all actiual values of system variables in Dr.Batcher. Tools -> Environment Variables:
We kindly remind that Dr.Batcher is the best program to create batch file, both .BAT and .CMD, try it if haven't tried it yet.

Monday, May 6, 2013

Difference between Call and Start

You may know that you can run a program or a batch file from your own batch file with the help of commands 'start' and 'call'. Both of them are used quite often, but what's the difference between them?
'Call' command pauses the execution of your batch file until the end of working of the called program or script. You can see it by creating a test batch file with a single 'pause' command. Save this test script as 'tst.cmd' and create batch file with text 'call tst' (no quotes). You'll see that your batch file waits for the end of execution of tst.cmd.
'Start' command starts the program or script in independent mode.  Change 'call' in your batch file to 'start'. You'll see that the main batch file closes its window while 'tst.cmd' is still running.
We kindly remind that Dr.Batcher is the best program to create batch file, both .BAT and .CMD, try it if haven't tried it yet. 

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!

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.

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.

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).

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.

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.

Thursday, December 30, 2010

Batch File for IP Change


There is a plenty of users that want to change the IP address of a computer with help of batch files. There is a simple way to perform it, all you need is standard netsh command and some imagination to 'invent' a new IP address.
The following line of code will help you to set the IP address and the subnet mask:
netsh int ip set address name = "LAN" source = static addr = 127.0.0.1 mask = 255.255.255.205
Of course, you have to use real IP address instead of samples given above (127.0.0.1 and 255.255.255.205).
Also we advice you to learn netsh command because it's really useful for different networking operations.

Friday, December 24, 2010

Batch File to Delete Itself

Sometimes users of Dr.Batcher ask us how to create a batch script that is able to delete itself. It is not hard, and the example of self-destructive script is placed in Dr.Batcher's installation package.
The trick is to call command-line processor (previously known as Command.com) with instruction to delete this batch file. While the processor is working, the source batch file will be already finished. Thus the processor will be able to delete it.
This is 'theory'. Practically you are to write the following batch code. Caution: do not run this file in folders with any valueable content, it may cause its loss or destruction.
REM Self-Deleting Batch Script
REM This script will delete all files in current folder, including itself

REM Don't forget to make backup copy of all files in current forder before its execution
ECHO This script will delete everything in current folder

ECHO Terminate it to cancel the action

PAUSE
@ECHO OFF

CD ..
START CMD /C RMDIR /S /Q "%~dp0"
The logic of whole the script is situated in the last construction. It starts the command-line processor and tells it to remove the whole directory where this batch script is placed. Of course, you can write additional batch file with this command instead. Also you can use 'DEL' instead of 'RMDIR' if you want to delete only batch file itself.

Saturday, December 11, 2010

Interesting Way To Delete Empty Folders through Batch Files

Deleting different garbage with help of batch files is quite a common task. Quite interesting way of solving this problem I have found on http://www.ehow.com/how_6648535_search-delete-empty-folders.html. The author of this article plays with parameters of DIR command to retrieve the names of all empty folders on a certain logical drive and then saves them to text file. After that this file should be renamed with extension BAT or CMD, and each line should start with "rd " before the directory's name. It's really interesting and quite unusual, but still fast and effective way to clear empty folders through batch files.
You should just remember that some applications require empty folders to be run, and removing these folders can make these applications useless till their re-installation.

Wednesday, November 10, 2010

How to Start or Stop a Windows Service with Help of Batch Files


Some users ask us how can they start Windows service with help of a batch script. That's why we decided to write a short post on this topic in our team's blog.
First of all it should be mentioned that starting or stopping some Windows services can make your system work strangely. Thus you should work with services really carefully, especially with standard services installed while the installation of the operating system.
Actually, you should know only one command to run or end Windows services. This command is called NET. To run a service you should add to your batch file the following line:
NET START "Service Name"
And to stop a service you have to use this construction:
NET STOP "Service Name"
Of course, you have to use the real name of the service you want to start or stop instead of Service Name.
It's really easy to work with services, as you see. If you have any questions about batch files, feel free to ask us via support@m-w-c-s.com.

Wednesday, October 6, 2010

Creating And Upacking ZIP Archives Using Batch Scripts

Sometimes it's necessary to create archives and extract files from them with help of batch files. For instance, it's useful when you writing scripts for automated backups. There is a number of different console archivers available on market, but still the most famous one is PKZIP (together with unpacker PKUNZIP). This archiver is especially useful for those who still use DOS for some reason.
The following command will help you to compress all files in the current forder:
PKZIP -a -ex -r -P -whs %1 *.*
If you put this line to a text file and save it as 'zip.bat', then you should just call 'zip.bat c:\archive.zip' to compress all files from the current folder to c:\archive.zip.
To extract files from the created archive to the current folder, you have to use the following command:
PKUNZIP -d %1 -o .\
The only parameter passing to this short batch file is the name of ZIP to be extracted.

Saturday, September 18, 2010

Checking for Existence of a File in Batch Scripts

Sometimes it is necessary to check whether a file exists in a certain folder. Batch scripting provides a programmer with a really nice construction called 'If Exist'. It's pretty useful when you want to check for existence of a given file, for example, 'autoexec.bat'. To check for it, you should write the following code:
If Exist autoexec.bat Echo Autoexec.bat exists!
But if you try to check for existence of any files in the way described above, you'll be surprised. Written '*.*', you'll be notified about existing files anyway, even when there are no files in the given folder. So instead of using '*.*' in 'if exist', it's better to look at the following code:
@Echo Off
For %%a In (1\*.*) Do Call :File_Ex %%a
If Defined FileExist Echo Exist
Goto :EOF
:File_Ex
Set FileExist=Yes
Goto :EOF
This code will give you proper answer about files in the specified folder, and you can include it into your own batch scripts. Hope it'll be useful for you.

Monday, January 4, 2010

Installing Fonts Using Batch Files

Installing fonts is not really common task performing every day by thousands of people. Still one day you can understand that you are to install fonts with help of batch scripting. Fortunately it's really won't take a lot of time to create a batch file to install several fonts. You should just copy them into Fonts directory and add some keys to the Registry. Here is the batch script you are to execute:
copy font.ttf %systemroot%\fonts
regedit /s font.reg
The only trouble is that you have to create REG-file first. It will take a few moments to add the following lines to font.reg:
REGEDIT4

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts]
"Font Name"="font.ttf"

Put down the real name of your font instead of "Font name" (leave commas). Also don't forget to reboot after the font's installation. That's all!

Thursday, December 3, 2009

Comments in Batch Scripts

Do you know how to comment a line in a batch script? Sure most of you know that it is possible with 'REM' at the start of certain line. But there are still some alternative ways. These ways are really popular among batch files creators but they can produce some unexpected errors while the execution of a batch file.
The most popular commenting style for batch scripts looks like this:
:: This is a comment
And the other one looks even simpler:
: This can also be a comment
You know that batch files syntax says that names of labels start with ":" character. So the comments above are labels for the batch files interpreter. And this is the source for some specific errors. For example, if you add such comment into blocks of code inside IF or FOR statements (between brackets), you'll see the error message. So you need to write comments before the beginning of such code block, or use traditional 'REM' instead of colons.

Monday, November 23, 2009

'Else' in Batch Files Conditions

The following version of Dr.Batcher, which is going to be released in a few days, will bring support for extended syntax of 'If' command. So we decided to give you some additional information on using 'Else' in batch file conditions.
The command after 'Else' keyword will be executed if the condition appears to be false. You should know that the whole 'If' statement must be written in the same line, so you cannot write your batch file in the following manner:
If errorlevel 1 Echo Error!
Else Echo Everything's OK!

But the following code will work perfectly:
If errorlevel 1 (
Echo Error!

) Else (
Echo Everything's OK!
)

Note that you can add extra commands between brackets and thus compose quite complex scripts.

Saturday, November 14, 2009

Cutting Characters in Batch Scripts

It's necessary sometimes to cut some characters from the value of a variable in a batch script. For example, you need to rename a file having a too long name, or need to pass a certain string as a parameter for another batch file and need to cut last 5 characters. How can you cut these characters from a string? There is really simple solution provided by the command interpreter. For example, if you want to cut last ten characters from the first parameter given to your batch file, use the following code:
SET param1=%1%
SET param2=%param1
:~0,-10%
In general, to cut a string from a variable, you should use one of the following constructions:
%var:~n,m%
%var:~n,-m%
%var:~n%

The first line cuts m characters from the string assigned to variable var, starting with n-th character (beginning from zero). The second line removes m characters from the string's tale. The third one cuts all characters in the string beginning with n-th character.

Tuesday, November 10, 2009

Batch Scripts and Windows Registry

One of the most common tasks you can meet during the batch scripts usage is modification of the Windows registry. It is likely that Microsoft still respects users of batch files because it provides them with several powerful tools allowing to add, delete or change registry keys and their values.
The most useful command is called reg. As it is stated in official manual, this command 'adds, changes, and displays registry subkey information and values in registry entries'.
There is no use in repeating words written by Microsoft, so I should just mention the alternative way to add keys or values to the registry. You can create REG file using your batch script and then call RegEdit to add keys described in this REG file to the registry. Of course, this way may look quite exotically, but it's really useful in some cases.

Translate