How to loop through files in a folder using MS DOS batch file or Commandline

PowerShell rocks but I still use DOS commands to automate many day to day tasks

Here is a script which can loop through files and perform whatever actions you want

As you can see that %%F will return full path of current file in the loop and %%~nF will return Filename without extension. If you calling this same script on commandline  then just use %F and %~nF (single % rather than %%)

Example Batch File: CopyFile.bat

ECHO ">>> Copy Files and Register in GAC <<<"

FOR /R "C:\Build" %%F in (*.dll) do ( 
copy "%%~F" "%PROGRAMFILES%\MyApp" /Y

gacutil.exe /u "%%~nF"
gacutil.exe /if "%%~F"

)

Here is another sample script and output which shows how to use various inbuilt variables to extract different parts of File Path we looping through

@echo off
FOR /R "E:\Backup\JVC-Camcoder\BACKUP_1" %%F in (*.mod) do ( 

MKDIR "C:%%~pF" 

ECHO **1** %%F
ECHO **2** %%~nF
ECHO **3** %%~xF
ECHO **4** %%~dF
ECHO **5** %%~pF
ECHO **6** %%~nxF
ECHO =======
)

Output :

A subdirectory or file C:\Backup\JVC-Camcoder\BACKUP_1\SD_VIDEO\PRG00D\ already
exists.
**1** E:\Backup\JVC-Camcoder\BACKUP_1\SD_VIDEO\PRG00D\MOV21B.MOD
**2** MOV21B
**3** .MOD
**4** E:
**5** \Backup\JVC-Camcoder\BACKUP_1\SD_VIDEO\PRG00D\
**6** MOV21B.MOD
=======
A subdirectory or file C:\Backup\JVC-Camcoder\BACKUP_1\SD_VIDEO\PRG00D\ already
exists.
**1** E:\Backup\JVC-Camcoder\BACKUP_1\SD_VIDEO\PRG00D\MOV21C.MOD
**2** MOV21C
**3** .MOD
**4** E:
**5** \Backup\JVC-Camcoder\BACKUP_1\SD_VIDEO\PRG00D\
**6** MOV21C.MOD
=======

Binary World is a Software Development company located in Atlanta, USA (since 2007). Binary World specialized in Business Intelligence, mobile, cloud computing and .Net Application Development.

Leave a Reply