views:

145

answers:

3
A: 

Prefix references to %1 with 1, as in %~1:

:next
if not "%~1" == "" (
    echo %~1

    shift /1
    goto next
)

(Why isn't this the default behaviour?)

There still seem to be quirks with commas from Explorer (a,b,c.exe is treated as several words), though. Can anyone help on that end?

strager
+1  A: 

The substitution modifiers for for variable references also allow for using the ~ expansions. See for command reference.

By using "%%~x" you should get a properly quoted parameter, similar to how bash handles "$@".

@echo off

setlocal enableextensions

for %%x in (%*) do (
    echo "%%~x"
)

The characters , and ; can be used to separate command parameters. See command shell overview. Thus you have to put quotes around file names that contain these characters.

If you drag a file from the Explorer onto the .bat, Explorer will only quote the file correctly if it has a white space character in its path. E.g., D:\a,b,c.exe will not be quoted by Explorer and thus will be parsed as three separate arguments by cmd.exe.

To make the script work with drag and drop from the Explorer for these freak cases, you can use the following (ugly) work-around:

@echo off

setlocal enableextensions enabledelayedexpansion

set "args=%*"
set "args=%args:,=:comma:%"
set "args=%args:;=:semicolon:%"

for %%x in (%args%) do (
    set "filepath=%%~x"
    set "filepath=!filepath::comma:=,!"
    set "filepath=!filepath::semicolon:=;!"
    echo "!filepath!"
)

The script introduces a helper variable args, where each occurrence of the troublesome characters is replaced with a placeholder (note that the colon character itself cannot be used in a file name under Windows).

The body of the for loop uses another helper variable filepath which undos the transformation to produce the original path.

sakra
Odd; Explorer doesn't seem to quote files with commas in their name, so the .bat has problems. This script functions just like my solution, except I guess it's a bit more robust.
strager
@stragerI have updated my solution to include a work-around for Explorer not quoting file names with ; , correctly.
sakra
Works great; thanks!
strager
A: 

I've created a batch "function" which does "proper" parsing of arguments and handles equal signs and semicolons correctly. I think you'll find that it can help you solve these problems. Full details and an example can be found on my site: http://skypher.com/index.php/2010/08/17/batch-command-line-arguments/

SkyLined
@SkyLined, I can't seem to access your link... Is the server down?
strager