Force quotes to protect DnD arguments

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
pcjco
Posts: 1
Joined: 05 Aug 2009 01:32

Force quotes to protect DnD arguments

#1 Post by pcjco » 05 Aug 2009 01:49

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 ?

avery_larry
Expert
Posts: 391
Joined: 19 Mar 2009 08:47
Location: Iowa

#2 Post by avery_larry » 05 Aug 2009 10:20

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.

jaffamuffin
Posts: 40
Joined: 25 Jan 2008 14:05

#3 Post by jaffamuffin » 21 Aug 2009 08:08

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.

Post Reply