How To Make A BAT File To Generate Multiple Files Automatically For Beginners

Have you ever needed to create a large number of text files in bulk? Manually creating each file one by one is not only time-consuming but also prone to errors. Fortunately, a simple BAT (Batch) file can solve this problem with just a double click. As shown in the video, the demonstrated BAT file can automatically generate 100 text files in the current directory immediately after running. Behind this magic is the built-in batch command of the Windows system, which is easy to learn even for beginners with no programming experience. In the following content, we will open the BAT file with VS Code, analyze the code line by line, and guide you through the principles and practical operations to fully master the method of batch file creation.

1. Set Character Encoding – Prevent Garbled Output In The Console

The first key step in creating a batch file for generating multiple files is to configure the correct character encoding. Improper encoding settings will cause garbled text in the console when running the script, affecting the operation experience and result viewing.

  1. Add the code `chcp 65001 > nul` as the first line of the BAT file. This command sets the output character set encoding of the console to UTF-8.
  2. Without this line of code, running the script directly will result in garbled text in the console due to encoding mismatch, making it impossible to view the execution status normally.
  3. After saving the code and running the script, the console will clearly display the execution process without any garbled interference, laying a solid foundation for subsequent operations.

2. Enable Delayed Variable Expansion – Ensure Normal Operation Of Loop Variables

When the Windows system executes a batch file, it interprets and executes the code line by line. For structures such as loops and if code blocks, it preprocesses variables first and then executes the entire block. This feature will cause variables in the loop to fail to update in real time, so delayed variable expansion needs to be enabled.

  1. Add the command `setlocal enabledelayedexpansion` after the encoding setting code to enable the delayed variable expansion function.
  2. After enabling this function, variables marked with two exclamation marks `!` in the loop (such as `!RANDOM!`) will be re-executed and updated in each loop.
  3. Without enabling delayed variable expansion, variables in the loop will remain their initial values, making it impossible to achieve requirements such as random number generation and dynamic filename changes.

3. Define Variables – Store Fixed Text Content

To make the batch-created files contain specified content, we can first define a variable to store the text content that needs to be written into the files for easy subsequent calls.

  1. Use the command `set “big_text=The fixed content you want to write into the files”` to define a variable named `big_text`.
  2. The string on the right side of the equal sign can be modified according to needs, such as inputting explanatory text, data templates, or other fixed content.
  3. After defining the variable, the content can be directly called by the variable name in the subsequent loop, eliminating the need for repeated input and simplifying the code structure.

4. Set Up A Numeric Loop – Control The Number And Rhythm Of File Creation

Looping is the core link of batch file creation. The `for /l` command can realize a fixed-number numeric loop to accurately control the number of files created, and at the same time, use pause commands to adjust the execution rhythm.

  1. The core loop code is `for /l %%i in (0,1,99) do (…)`, where `for /l` indicates the numeric loop type.
  2. `%%i` is the name of the loop variable. The three parameters in the brackets are: start value (0), increment per loop (1), and end value (99), which means the loop will be executed 100 times (from 0 to 99).
  3. In the loop body, first call the system’s built-in random number variable through `!RANDOM!` to generate a unique identifier for each file.
  4. Use the command `echo !big_text! > File_Name_!RANDOM!.txt` to write the content of the defined variable into the newly created text file. The filename is combined with a random number to ensure uniqueness.
  5. Add the command `echo Creating file: File_Name_!RANDOM!.txt` to display the current creation progress in the console for real-time viewing.
  6. Insert the `pause` command (can be added or removed as needed) to debug the script, which pauses during execution to facilitate checking the execution result of each step.
  7. Add the command `timeout /t 0 /nobreak >nul` to control the rhythm of file creation: `/t 0` means pausing for an extremely short time (almost imperceptible), `/nobreak` prohibits terminating the program with Ctrl+C, and `>nul` shields the default output of the timeout command.

5. Conclusion: Practical Verification And Expansion – Make Batch Operations More Efficient

After completing the code writing, save the BAT file, return to the directory where the file is located, and double-click to run the script to start the batch creation process. The console will sequentially display the creation status of each file. After execution, 100 text files containing the specified content will appear in the current directory, with unique filenames.

Through this case, we not only learned how to batch create files but also mastered core skills such as encoding settings, variable definition, and loop control of batch scripts. These skills can be flexibly expanded, such as modifying loop parameters to change the number of files, adjusting variable content to modify file templates, and adding commands to realize classified storage of files. Whether it is batch document generation in an office scenario or test file creation during the learning process, this BAT script can help you save a lot of time and improve work and learning efficiency.

6. Source Code

@echo off
:: Disable the default command echo function in the command line to keep the output interface clean (only shows content from echo commands in the script)

chcp 65001 > nul
:: Set chcp 65001: Change command line encoding to UTF-8 to avoid garbled characters in output
:: > nul: Hide the execution prompt of this command so it doesn't clutter the console

setlocal enabledelayedexpansion
:: Enable delayed variable expansion
:: Purpose: In loops or code blocks, use !variable_name! to get the latest variable value in real time (default %variable_name% parses in advance)

set "big_text=The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking."
:: Define a variable named big_text and assign it a fixed text string
:: This text will be written into each batch-created file later

for /l %%i in (0,1,99) do (
    :: for /l: Indicates a numeric loop, used to execute commands repeatedly with a fixed step
    :: %%i: Loop variable (batch files require two % symbols for loop variables)
    :: (0,1,99): Loop parameters - start value, step size, end value
    :: Executes 100 times total (from 0 to 99, incrementing by 1 each time)

    set random_num=!RANDOM!
    :: !RANDOM!: Call the system's built-in random number variable (generates 0-32767 random integer)
    :: Assign the random number to custom variable random_num for later use

    echo !big_text! > Test_%%i_!random_num!.txt
    :: echo !big_text!: Output the content of the big_text variable
    :: > Test_%%i_!random_num!.txt: Write output to a file
    :: Filename format: Fixed prefix (Test_) + loop variable (%%i) + random number (!random_num!)
    :: Function: Create a unique text file and write the preset content into it

    REM pause
    :: REM: Batch comment command - this line is commented out and won't execute
    :: pause: Originally used to pause script execution (commented to speed up batch processing)

    echo Creating file: Test_%%i_!random_num!.txt
    :: Display the current file being created in the console for progress tracking

    REM pause
    :: Another commented pause command - for step-by-step debugging (not needed for normal execution)
    
    REM timeout /t 0 /nobreak >nul
    :: timeout /t 0: Pause the script for 0 seconds (extremely short delay to control execution rhythm)
    :: /nobreak: Prevent interrupting the pause with Ctrl+C
    :: >nul: Hide the default output of the timeout command
    :: Uncomment this line if you need to adjust the file creation speed
)

endlocal
:: Terminate the local environment for delayed variable expansion (matches setlocal enabledelayedexpansion)

echo All files created successfully!
:: Prompt in the console that the batch file creation process is complete

pause
:: Pause the script to prevent the command line window from closing automatically, letting the user review results

7. Demo Video

You can watch the following demo video by select the subtitle to your preferred subtitle language.

https://youtu.be/eN7Yhr7RUzc

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.