Find the latest sub-folder within a directory only if that directory exists batch script

255 Views Asked by At

I am trying to find most recent sub-folder within a directory only if that directory exists. My code does not give me any output when I use FOR loop within IF statement. Here is my code -

@echo off
IF EXIST "D:\MyDirectory" (
    FOR /F "delims=" %%i IN ('dir "D:\MyDirectory" /b /ad-h /t:c /od') DO SET abc=%%i
    echo Most recent subfolder: %abc%
) ELSE (
    echo Directory not found
)

My code works fine separately

1. To check separately if the directory exists,

IF EXIST "D:\MyDirectory" (
    echo Directory exists
) ELSE (
    echo Directory does not exists
)

2. To find the most recent folder,

FOR /F "delims=" %%i IN ('dir "D:\MyDirectory" /b /ad-h /t:c /od') 
DO SET abc=%%i
echo Most recent subfolder: %abc%

Basically I get correct output of the most recent folder when I don't combine the FOR loop and the IF statement. What I am observing here is, the code echos blank output for the variable 'abc' when we use FOR loop within IF statement. My question is, doesn't batch script allow us to use FOR loop within an IF statement? If so, is there any workaround I could do here to achieve the desired outcome?

1

There are 1 best solutions below

1
On BEST ANSWER

Yes, you can have FOR inside IF.

In your code, %abc% is being expanded in your nested echo statement when the entire IF statement is read, before your set statement assigns it. If you look at abc after the for look exits, abc should be set properly. You can also try setting ABC to a telltale value like FOO before you execute the IF statement, and you will see that it echoes the telltale value. It will be properly set after the IF executes.

setlocal enabledelayedexpansion
IF EXIST "D:\MyDirectory" (
FOR /F "delims=" %%i IN ('dir "D:\MyDirectory" /b /ad-h /t:c /od') DO SET abc=%%i
echo Most recent subfolder: !abc!
) ELSE (
echo Directory not found
)

What you need to do is enable delayed expansion, and then echo !abc! instead of %abc%.

Type "help set" and look for "Delayed environment variable expansion" for more details.

Another approach would be to replace your echo statement with a call to a subroutine outside the IF statement. The call statement itself will be when the IF statement is parsed, but the statements in the subroutine will be evaluated normally.

Note that loop control variable %%i is not resolved before the loop executes - that can remain with % signs.