Home > OS >  How to loop through directory files using IF THEN and variables?
How to loop through directory files using IF THEN and variables?

Time:10-22

I have a directory with files and a ControlFile.txt that contains the a list of SHA256 sums for various files. I'm trying to come up with a Batch process to loop through the files in the directory, calculate the SHA256 value of each file, and then compare whether or not the calculated SHA256 exists or not in the ControlFile.txt and branch accordingly.

I've attempted to produce a working script with the following but I believe I'm missing some key elements:

for /R . %%f in (*.*)  do (
find /c "(certutil -hashfile "%%f" SHA256 | findstr /V "hash")" ControlFile.txt > NUL
    if %errorlevel% equ 1 goto notfound
        echo "%%f" found
    goto done
    :notfound
        echo "%%f" notfound
    goto done
    :done)

I believe I may need to set a variable for the given SHA256 value and use that within the loop to produce the comparative function I'm trying to achieve, but my knowledge with batch files and cmd is limited. Any code advice would be greatly appreciated.

CodePudding user response:

@ECHO OFF
SETLOCAL
rem The following settings for the source directory and filename are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
SET "filename1=%sourcedir%\q74148620.txt"

FOR /f "delims=" %%b IN ('dir /s /b /a-d "u:\j*" ') DO (
 FOR /f %%y IN ('certutil -hashfile "%%b" SHA256 ^| find /V ":"') do (
  findstr /x "%%y" "%filename1%" > NUL
  IF ERRORLEVEL 1 (
   ECHO "%%b" NOT found
  ) ELSE (
   ECHO "%%b" found
  )
 )
)

GOTO :EOF

I used a filemask of j* for testing - change to suit.

Simply run the certutil routine on each file in turn, filter out any lines that contain :, leaving the SHA256 data. Locate that value as /x an exact mach to a line in the SHA256 values file. If a match is found, errorlevel is set to 0, non-0 otherwise, then switch on errorlevel.

  • Related