I want to create a batch script that will print all the files I have in a folder, in order of dat...

Learn i want to create a batch script that will print all the files i have in a folder, in order of date modified with practical examples, diagrams, and best practices. Covers windows, batch-file, ...

Print Files by Date Modified in a Batch Script

Hero image for I want to create a batch script that will print all the files I have in a folder, in order of dat...

Learn how to create a Windows batch script to list and print files from a specified folder, ordered by their last modification date.

Organizing and managing files often requires specific sorting criteria. One common need is to list or print files based on their modification date. This article will guide you through creating a simple yet effective Windows batch script that identifies all files within a given directory and its subdirectories, sorts them by their 'Date Modified' attribute, and then outputs this list to a text file, which can then be printed. This method is particularly useful for auditing changes, archiving, or simply getting an ordered overview of recent activity in a folder.

Understanding the Core Commands

To achieve our goal, we'll leverage a few fundamental Windows command-line utilities. The FORFILES command is powerful for iterating through files and executing a command on each. However, it lacks direct sorting capabilities by date. A more flexible approach involves combining DIR for listing files with SORT for ordering them, and then redirecting the output. The DIR command, when used with specific switches, can provide detailed file information, including modification dates, which SORT can then process.

flowchart TD
    A[Start Batch Script] --> B{Define Target Folder}
    B --> C[List Files with DIR /O:D /S]
    C --> D[Extract File Paths and Dates]
    D --> E[Sort by Date Modified]
    E --> F[Output to Temporary File]
    F --> G[Print Temporary File (Optional)]
    G --> H[Clean Up Temporary File]
    H --> I[End Script]

Workflow for listing and printing files by date modified.

Creating the Batch Script

The following batch script will perform the necessary steps. It will ask the user for the target folder, then use the DIR command to list all files, including those in subdirectories (/S), sorted by date (/O:D). The output is then formatted and saved to a temporary text file. Finally, it provides an option to print this file and cleans up the temporary file.

@echo off
setlocal

:: --- Configuration ---
set "outputFile=FileListByDate.txt"
set "tempFile=temp_print_list.txt"

:: --- Get User Input ---
set "targetFolder="
set /p "targetFolder=Enter the full path to the folder you want to list (e.g., C:\MyDocuments): "

if not exist "%targetFolder%" (
    echo Error: The specified folder does not exist.
    goto :eof
)

:: --- Generate File List ---
echo Generating file list for: "%targetFolder%"...

:: Use DIR to list files, sorted by date (oldest first), including subdirectories
:: /A:-D excludes directories themselves
:: /B uses bare format (just file names)
:: /O:D sorts by date/time (oldest first)
:: /S includes subdirectories

:: For more detailed output including date/time:
:: dir "%targetFolder%" /A:-D /O:D /S > "%tempFile%"

:: To get a more structured output with date and path, we need to parse DIR's output.
:: This approach captures date, time, and full path.

(for /f "tokens=1-4*" %%a in ('dir "%targetFolder%" /A:-D /O:D /S ^| findstr /v /b /c:" Volume in drive" /c:" Directory of" /c:"File Not Found" /c:"Total Files Listed" /c:" Total files" /c:" bytes" /c:"Free Bytes"') do (
    set "line=%%a %%b %%c %%d %%e"
    echo !line!
)) > "%tempFile%"

:: --- Format and Sort (if necessary, though DIR /O:D already sorts) ---
:: The above DIR command with /O:D already sorts by date. 
:: If you needed custom sorting (e.g., newest first from a different DIR output),
:: you would use 'sort /r' here. For this script, DIR's sorting is sufficient.

:: --- Output to Console and File ---
echo.
echo File list sorted by date modified (oldest to newest):
more < "%tempFile%"

echo.
echo The full list has been saved to "%outputFile%" in the current directory.
copy "%tempFile%" "%outputFile%" >nul

:: --- Print Option ---
set /p "printChoice=Do you want to print this list now? (Y/N): "
if /i "%printChoice%" equ "Y" (
    echo Sending "%outputFile%" to default printer...
    :: Use 'print' command for simple text printing. 
    :: Note: 'print' is a basic command and might not work with all printers/drivers.
    :: For more robust printing, consider using a third-party utility or PowerShell.
    print "%outputFile%"
    if errorlevel 1 (
        echo Warning: Could not send to printer. Please print "%outputFile%" manually.
    ) else (
        echo Print job sent.
    )
) else (
    echo Printing skipped.
)

:: --- Cleanup ---
del "%tempFile%"
echo.
echo Script finished. "%outputFile%" remains in the current directory.
endlocal
pause

Batch script to list and print files by date modified.

How the Script Works

  1. @echo off: Prevents commands from being displayed in the console.
  2. setlocal: Creates a local environment for variables, ensuring they don't affect the system after the script finishes.
  3. Configuration: Defines the names for the final output file and a temporary file.
  4. User Input: Prompts the user to enter the path of the folder they want to process. It includes basic error checking to ensure the folder exists.
  5. Generate File List: This is the core part. The dir command is used with several switches:
    • /A:-D: Excludes directories from the listing, showing only files.
    • /O:D: Sorts the output by date and time, oldest first. Use /O:-D for newest first.
    • /S: Includes files in all subdirectories.
    • The output of dir is piped (|) to findstr to filter out header/footer lines, leaving only the file entries. The for /f loop then processes each relevant line, capturing the date, time, and full path.
    • The formatted output is redirected (>) to a temporary file (%tempFile%).
  6. Output and Copy: The script displays the content of the temporary file to the console using more and then copies it to the final outputFile.
  7. Print Option: Asks the user if they want to print the generated list. If 'Y', it uses the print command. An errorlevel check provides basic feedback on the print job.
  8. Cleanup: Deletes the temporary file, leaving only the final FileListByDate.txt.

1. Save the Script

Open Notepad or any plain text editor. Copy and paste the entire batch script provided above into the editor. Save the file with a .bat extension (e.g., PrintFilesByDate.bat). Make sure to select 'All Files' as the 'Save as type' to prevent it from being saved as a .txt file.

2. Run the Script

Navigate to the location where you saved the .bat file using File Explorer. Double-click the file to execute it. A command prompt window will open.

3. Enter Folder Path

The script will prompt you to 'Enter the full path to the folder you want to list'. Type or paste the path (e.g., C:\Users\YourName\Documents) and press Enter.

4. Review and Print

The script will process the files and display a preview of the sorted list. It will then ask if you want to print the list. Type Y for Yes or N for No, then press Enter. If you choose to print, the list will be sent to your default printer.

5. Check Output File

Regardless of whether you print, a file named FileListByDate.txt will be created in the same directory as your batch script. This file contains the complete list of files sorted by date modified.