Quizzed
Quizzed

Reputation: 173

Command works on command line, but operates unexpectedly in batch file

I have this simple batch code to check the Date Modified on a sub-folder (specifically the Recycle Bin.) This search works flawlessly when manually input in Command Prompt, but not batch.

And using the same exact code to check other folders it works just fine. Help?

Code:

if exist C:\$Recycle.Bin (
pushd "C:\$Recycle.Bin"
for /F "delims=" %%a in ('dir /S /b S-1-*-1001 /AD') do set {file}=%%a
for %%a in ("%{file}%") do echo Recycle Bin: %%~ta
popd
)

Upvotes: 0

Views: 86

Answers (1)

John Kens
John Kens

Reputation: 1679

The reason this is not working in batch is for one annoying feature of IF statements with the SET command. As stated by This Post - "cmd expands variables when commands are parsed, not when they are run. It so happens that an if or for statement with a block ( ... ) (or actually any block) counds as a single command in that case. So when you set variables inside a block and try using them in the same block there are no variables anymore – they were replaced by the values the variables had before the block even executed." - Joey

To fix this you can simply not put your code block inside the IF statement but rather use an ELSE and have it goto an :EOF

Option 1: - Avoid IF Statement W/H Code Block

@ECHO OFF

Rem | Check If Directory Exists & pushd It.
if exist "C:\$Recycle.Bin" (pushd "C:\$Recycle.Bin") ELSE (goto :EOF)

Rem | Grab data on folders
for /F "delims=" %%a in ('dir /S /b S-1-*-1001 /AD') do (set "{File}=%%a")

Rem | Display data on folders
for %%a in ("%{file}%") do (echo Recycle Bin: %%~ta)

Rem | Un-pushd
popd

pause
goto :EOF

If you do however wish to use a block inside the IF statment you will need to use setlocal enabledelayedexpansion at the top of your script. Furthermore, to echo or read brackets you will have to use !{File}! over %{File}%.

Option 2: - Properly expand IF Statement W/H Code Block

@ECHO OFF
@setlocal enabledelayedexpansion

if exist "C:\$Recycle.Bin" (

    pushd "C:\$Recycle.Bin"
    for /F "delims=" %%a in ('dir /S /b S-1-*-1001 /AD') do (set "{File}=%%a")
    for %%a in ("!{file}!") do (

        Set "data=%%~ta"
        echo Recycle Bin: !data!

    )
    popd

) Else (Goto :EOF)

pause
goto :EOF

Upvotes: 3

Related Questions