1

Why does this batch script work...

@echo off
for /F %%a in ('dir /b F:\Temp\*.txt') do set TestFileName=%%~nxa 
echo %FileName%
pause

But this one does not...

@echo off
for /F "usebackq" %%a in ('dir /b "F:\Temp Folder\*.txt"') do set TestFileName=%%~nxa 
echo %FileName%
pause

I know that it has something to do with the double quotes that I am using due to the spaces in the folder name. But even after hours of searching the web and reading countless posts that are similar, I can't for the life of me figure out how to fix it. And it is driving me CRAZY!!!

Any help would be greatly appreciated...

1
  • The option "usebackq" means that you have to use backquotes (a.k.a. back ticks or grave accent or `) to run a command. Change ' to `. The command help for discusses this. Commented Dec 7, 2012 at 2:19

1 Answer 1

1

Three points here:

1- As "usebackq" imply: Use Back Quotes for command execution, so you must put ` instead of '.

2- Independently of the above, this code:

@echo off
for /F "usebackq" %%a in (`dir /b "F:\Temp Folder\*.txt"`) do set TestFileName=%%~nxa 
echo %FileName%
pause

does NOT work either, because the shown variable FileName is NOT the same of the FOR command: TestFileName.

3- I strongly suggest you to NOT use a FOR /F command that execute another command (like DIR) if the base capabilities of simple FOR are enough for your needs. For example:

@echo off
for %%a in ("F:\Temp Folder\*.txt") do set TestFileName=%%~nxa 
echo %TestFileName%
pause

Previous code is not just easier to write and understand, but it run faster also.

Finally: previous code "works" in the sense that display just the last file name. If you want to display all names via a variable, then a different approach must be used.

I hope it helps...

Antonio

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.