Batch file fails strangely checking number of arguments

D

David Mayerovitch

I want to write a batch file to perform operations on one data file only.
Working in Windows Explorer, I want to drop the data file on the batch file;
the batch file must first check to see that only one file has been dropped
on it.

My first attempt in ARGTEST01.BAT, below, checks the second filename
argument "%2"; if it is not an empty string, there are too many arguments,
and control should be transferred to label :TOOMANY for the error message.

The batch file works fine when there is only one file dropped onto it;
however, if there are two or more dropped, execution terminates without
showing the warning or recognizing the "pause" command.

I got it to work in ARGTEST02.BAT by checking instead the variable "%~d2",
which returns the drive letter of the second filename argument rather than
the full filename.

I'm running Windows XP Home with SP2.

Can anybody figure out why the first version is not working? In fact, do you
get the same result as I do?

I'm wondering if the length of the pathnames has anything to do with it.
When I use test data files in the root directory of C:, ARGTEST01.BAT works
correctly with two files dropped on it, but fails with three!

Is there a more direct way of checking the number of arguments?

Thanks.

David

============================
ARGTEST01.BAT - faulty
============================
@echo off
if "%2" NEQ "" goto TOOMANY
echo Arguments OK.
pause
REM Do the actual work here ...
exit
:TOOMANY
echo Too many arguments!
pause
exit

============================
ARGTEST02.BAT - works fine
============================
@echo off
if "%~d2" NEQ "" goto TOOMANY
echo Arguments OK.
pause
REM Do the actual work here ...
exit
:TOOMANY
echo Too many arguments!
pause
exit
============================
 
D

David Mayerovitch

I think I have figured this out. When a command-line argument created by a
file dropped onto the batch file contains spaces, DOS delimits it with
quotation marks. If you then have a statement like:

if "%2" NEQ "" goto TOOMANY

then the expansion of "%2" will look like this:

""C:\My files\foobar.txt""

and the two sets of quotation marks will somehow mess things up.

I find in handling these command-line variables which represent filenames it
is more reliable to use the NT extensions like %~f1, which will return
drive, path and filename with spaces intact but without quotation marks.
Safest of all are those extensions like %~sp1, which returns the short path,
guaranteed to contain no spaces.

Any further thoughts on these problems would be welcome.

And if anyone knows of a clear and complete book on DOS batch file
programming, please let me know.

Thanks.
David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top