Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
i am not sure if any of these ideas will help but you know %1 %~f1 makes it full. Also, dir /b doesn't seem to give the full path, but dir /b /s does, though i guess you don't want /s. another thought is you can cut bits off of an environment variable e.g. echo abc , then echo %a:~1,2% not sure if that's useful to you – barlop Jan 31 '11 at 7:34
if "%~1"=="" (set dir=.) else (set dir="%~1")
if "%~2"=="" (set command=echo) else (set command=%~2)
if "%~3"=="" (set mask=*) else (set mask=%~3)
for /r %dir% %%f in (%mask%) do %command% %%~dpnxf

Or simply:

C:\>for /r . %f in (*) do @echo %~dpnxf
share|improve this answer
I didn't use the FOR /R %_DIR% %%f IN (%_FILTER%) DO syntax because I wanted support for recursion. – palswim Dec 16 '10 at 23:33

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.