Search code examples
batch-filedelayedvariableexpansion

Delayed expansion errors


I'm playing around with batch files and delayed expansions.
I am simply attempting to print the file/folder names of all items within a directory.

@ECHO off

SET title=%1
SET mp4="mp4"
SET mkv="mkv"
SET avi="avi"
SET minimumSize=300

CD "E:\Documents\Films\Need_compressing"
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%i IN (*) DO (
    SET item = %%i
    ECHO !item!
    :: print dir/file name
    :: if "!i!" == "%title%" (
    ::  echo "found file!"

    :: 'if' directory
    ::  if exist "%title" (
    ::      echo "is a directory"
    ::      cd %title%
    ::      echo "title: " %title%
    ::      for %%f in (*.*) do (

    ::          set file = %%f
    ::          set extension = %%~xf
    ::          set fileSize = %%~zf

    ::          if %extension% == %mp4% if %extension% == %mkv% if %extension% == %avi% (
    ::              if %fileSize% gtr %minimumSize% (
    ::                  move %file% %compressFolder%
    ::              )
    ::          ) 
    ::      )
    ::  )
    ::)
)
ENDLOCAL

When I do this, I would get the error:

The syntax of this command is incorrect

The only thing I can think of is that I'm using the delayed expansion wrongly.


Solution

  • The reason for the syntax error is because :: are not for comments. They're actually label markers. Use REM for comments.

    Other issues...

    Remove the spaces around the =

    SET item=%%i
    

    You also don't have to use delayed expansion if you use call.

    CALL ECHO %%item%%
    

    Also, keep in mind this FOR command will only show you files (no folders). If you want folder and files, just use DIR /B (no FOR). If you want to process them, you can use FOR /F like this:

    FOR /F "delims=" %%a IN ('DIR /B') DO ( echo do stuff with "%%~a" )
    

    (edit) Based on your updated file, you might also wish to use CD /D which will switch to your E: (unless you're already on E:, in which case you don't need it).