Reputation: 13
How to avoid delayed expansion removing the exclamation marks in file names?
@echo off
Set path="C:\example"
Set chars=a b c
cd /d %path%
setlocal EnableDelayedExpansion
for %%A in (%chars%) do (
set filesList=
for /F "tokens=* delims=" %%B in ('dir %%A^* /a-d /b') do (
set filesList=!filesList!"%%~nxB"
)
if not "!filesList!"=="" (
echo %%A filesList: !filesList!
)
)
endlocal
Upvotes: 1
Views: 873
Reputation: 82247
As Mofi suggested, you could disable delayed expansion and use
call set filesList=%%filesList%%"%%~nxB"
But that fails when there are carets in your filenames.
The problem in your code is the fact, that FOR parameters can only be safely expanded without delayed expansion mode.
Normally you use the toggline technic for this, like here.
setlocal DisableDelayedExpansion
for /F "delims=" %%B in ('dir %%A^* /a-d /b') do (
set "line=%%B"
setlocal EnableDelayedExpansion
REM *** Process the content of line here
echo !line!
endlocal
)
But this only works, when you don't need to transfer the content of line
out of the (inner) setlocal scope.
In your case, you tried to add the line
content to a filesList
variable outside of the scope.
For this case you need to transfer the content of line
over the scope end with a more or less complex technic, like
Make an environment variable survive ENDLOCAL
Macro to return multiple variables across endlocal barriers
Upvotes: 1