Reputation: 11
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...
Upvotes: 1
Views: 2748
Reputation: 67216
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
Upvotes: 1