Pooyan Shabani

Graphic designer

Web developer

Multimedia designer

Pooyan Shabani
Pooyan Shabani
Pooyan Shabani

Graphic designer

Web developer

Multimedia designer

Blog posts

File Categorization with a Batch File

May 27, 2023 mswindows
File Categorization with a Batch File

n this article, we will discuss how to categorize files using a batch file. This batch file allows you to categorize all the files in a folder based on their format. This can be very useful as it allows you to easily find related files and keep them organized.

Steps:

  1. First, open a batch file.
  2. In the first line of the batch file, use the “setlocal enabledelayedexpansion” command to enable the use of local variables in the batch file.
  3. In the next line, save the current directory path using “set “current_dir=%cd%””.
  4. Create a new directory named “yourname” using “mkdir “yourname” 2>nul”.
  5. Using a for loop, extract the name and format of each file in the folder.
  6. If the format of the file is not empty and not equal to “.bat”, “.zip”, or “.rar”, move it to the directory corresponding to its format.
  7. Using a for loop, for each directory in the current directory, if a file with the format “.zip” or “.rar” exists, move that directory to a new directory corresponding to that format.
  8. Finally, return to the current directory and display the message “Done.”.

The batch file code is as follows:

				
					@echo off
setlocal enabledelayedexpansion

set "current_dir=%cd%"

mkdir "yourname" 2>nul

for %%F in (*) do (
    set "filename=%%~nF"
    set "ext=%%~xF"
    
    if not "!ext!"=="" (
        if not "!ext!"==".bat" (
            if not "!ext!"==".zip" (
                if not "!ext!"==".rar" (
                    set "ext=!ext:~1!"
                    mkdir "yourname\!ext!" 2>nul
                    move "%%F" "yourname\!ext!"
                )
            )
        )
    )
)

for /d %%D in (*) do (
    if exist "%%D.zip" (
        mkdir "zip" 2>nul
        move "%%D" "zip\%%D"
        move "%%D.zip" "zip\%%D.zip"
    )
)

for /d %%D in (*) do (
    if exist "%%D.rar" (
        mkdir "rar" 2>nul
        move "%%D" "rar\%%D"
        move "%%D.rar" "rar\%%D.rar"
    )
)

cd "%current_dir%"

echo "Done."
pause
				
			

Result:
Now, using this batch file, you can categorize all the files in a folder based on their format and keep them organized. This allows you to easily find related files and keep them organized. Additionally, thismethod allows you to easily find and organize folders containing compressed files separately from other files. As a result, working with files becomes easier for you in general, and you can use your files in the best possible way.

source: learn microsoft

Taggs:
Write a comment