Page 1 of 1

Force quotes to protect DnD arguments

Posted: 05 Aug 2009 01:49
by pcjco
Hi,

I want to do a DOS script that do some stuff with the files that are passed as arguments (by drag and drop files to the script), but I have encountered special cases where the script cannot retrieve the argument correctly : short file name with special character like & (ampersand).

Imagine the simple script :
@echo %*

Here are the results when I Drag & Drop some files to this script
--> DnD C:\file.txt
C:\file.txt

--> DnD C:\a&b.txt
C:\a

--> DnD C:\a & b.txt
"C:\a & b.txt"

The problem is when the filename doesn't have space but has some ampersand (second example). In that case, it is not automatically surrounded by quotes and the ampersand is incorrectly interpreted.
If I force a space to the filename (third example) , then DOS will protect my argument by quotes and the ampersand is correctly kept in the filename.

Is there a trick to work with any filename passed to my script ?

Posted: 05 Aug 2009 10:20
by avery_larry
I strongly doubt that you'll make it work, because I believe it's not the batch file which has a problem, but rather the command line itself.

Take this code for example:
test.cmd

Code: Select all

@echo off
echo "%*"
echo Finished with this script.


and then run (from a command line, not drag-n-drop, so you can see what happens):

test c:\a&b.txt

You'll get the following output:
"c:\a"
Finished with this script.
'b.txt' is not recognized as an internal or external command,
operable program or batch file.

What's happening is that cmd.exe sees the original command line as 2 separate commands on one line using the &:

test c:\a
b.txt

It seems to be a mistake of explorer's drag-n-drop that it doesn't quote the filename when it has &.

I don't think I can do anything for you, other than the obvious -- get rid of filenames with & or make sure they have a space in them.

Posted: 21 Aug 2009 08:08
by jaffamuffin
Or possibly drag and drop the folder containing the dodgy files.

Then use a For loop on dir %1 /b /a-d to get the file names.