0
votes

I'm working with windows' cmd and trying to set a variable in a loop. Here's the code I have:

for /d %%a in ("F:\backup*") do set folder=%%a
ECHO %folder%
PAUSE

I want to look for a folder with name starting with "backup" on drive F and save that folder's name to %folder% variable. So for example if the folder would be called "backup 2017-01-18" I'd like that saved to a var.

Instead it doesn't seem to set anything as the ECHO just prints that "ECHO is on". The for loop is correct and the folder is there as well (I'm already using that piece of code for other batch with robocopy).

I could theoretically put all my code inside the FOR loop and use %%a instead of the %folder% var but that seems like a hacky solution.

All the solutions I found so far pointed to using EnableDelayedExpansion. I modified the code to use it like that:

Setlocal EnableDelayedExpansion
for /d %%a in ("F:\backup*") do set folder=%%a
ECHO !folder!
PAUSE

But now ECHO prints "!folder!" as if it would not detect the variable. If I revert to ECHO %folder% I once again learn that "ECHO is on".

EDIT: I found the issue here. I was also running another batch file on the backup folder. It turns out that ROBOCOPY (which I used in that batch) is setting the enclosing folder to hidden, system and readonly by default (even if copied files are not hidden or system o_0). When I removed HSR attributes on the directory the code posted here started working fine (the initial version).

1
Is this set of code inside another code block? Your first set of code works just fine for me by itself. - Squashman
No, this is the entire batch file that I run manually. - ilozen
Then F:\backup* does not exist. - Squashman
I found the issue and edited my post - it's because robocopy sets hidden, system and read-only flags on enclosing folder - this prevented my FOR loop from executing. - ilozen
If you found the answer to your problem, please add it as answer and accept it (I think you will have to wait 2 days before accepting though). - geisterfurz007

1 Answers

1
votes

If your loop for /d %%a in ("F:\backup*") do does not detect any directories whose names begin with backup, they either do not exist or there are the attributes hidden and/or system set.

To detect also such hidden or system directories, replace the for /D loop by this:

rem Change to parent directory "F:\" temporarily in order for the `~f` modifier to resolve the full path properly:
pushd "F:\" || exit /B 1
for /F "eol=| delims=" %%D in ('dir /B /A:D /O:N "backup*"') do set "folder=%%~fD"
popd