How to ensure full path in Windows batch FOR loop

Posted by palswim on Super User See other posts from Super User or by palswim
Published on 2010-12-16T22:57:26Z Indexed on 2011/01/31 7:28 UTC
Read the original article Hit count: 555

Filed under:
|
|

I've created a generic batch (or Windows Command) file that lets me loop through the contents of a directory and call a command for each item.

IF a%1==a ( set _DIR="%CD%") ELSE ( set _DIR="%~1")
IF a%2==a ( set _COMMAND=rem) ELSE ( set _COMMAND=%2)
IF a%3==a ( set _FILTER=*.*) ELSE ( set _FILTER=%3)
set _OPTS=%4

FOR /F "delims=" %%f IN ('dir %_DIR%\%_FILTER% %_OPTS% /b') DO (
%_COMMAND% "%%f"
)

But, I'm trying to determine how to ensure that I call %_COMMAND% on the correct file.

I've tried pre-pending the directory variable onto the front, like %_COMMAND% %_DIR%\"%%f", but this leaves a quotation mark in the parameter I pass. For example, if I call my batch file exec_dir.bat, and call it with the following echo_test.bat, I see that all of the files have a quotation mark when echo_test.bat runs.

echo %~dpn1.mp4

That batch script produces:

> exec_dir.bat "C:\Users\User\Desktop\Test Folder" echo_test.bat *.txt
C:\Users\User\Desktop\Test Folder\"Test File.txt
C:\Users\User\Desktop\Test Folder\"Test2.txt

My thought is that it has something to do with the \ as an escape character, but I can't seem to work around it.

© Super User or respective owner

Related posts about Windows

Related posts about batch