Nizamuddin Sam
Nizamuddin Sam

Reputation: 11

Batch file to generate list of files

Can someone help me on creating a batch file, which will list the below details as csv file output?

- file name
- Date creation
- Modified date
- File size

Basically my batch file should run from a root directory which contains multiples sub directories and files. I tried with some limited knowledge & with the help of googling below script.

As of now I am getting the output as file name, creation & modification field from root directory. But I'm not able to generate if multiple files & folders inside. I don't get file size, too.

@echo off

setlocal EnableDelayedExpansion
(
  echo "Name","Modification Time","Creation Time"
  for %%f in (*) do (
    set "name=%%~nxf"
    if not "!name!"=="%~nx0" (
      set "mtime=%%~tf"
      for /f "tokens=1-3" %%d in (
        'dir /t:c "!name!" ^| find /i "!name!"'
      ) do set "ctime=%%~d %%~e %%~f"
      echo "!name!","!mtime!","!ctime!"
    )
  )
) > FileList.csv

Upvotes: 1

Views: 216

Answers (2)

TessellatingHeckler
TessellatingHeckler

Reputation: 29048

Call out to PowerShell, which is good at this kind of thing.

powershell "ls -R|select FullName,LastWriteTime,CreationTime,Length|Export-Csv x.csv -NoT"

Upvotes: 1

rojo
rojo

Reputation: 24476

If not for the "creation time" requirement, you could use tilde expansion in a for /R loop, like

@echo off & setlocal

>FileList.csv (
    for /R %%I in (*) do echo "%%~fI","%%~tI","%%~zI"
)

In a console window, enter for /? for full details about for /R and tilde expansions.

Unfortunately, acquiring a file's creation time requires either a second dir command with the /T:C switch, or a wmic command (slower). Here's a solution that employs dir /T:C:

@echo off & setlocal

>FileList.csv (
    set "created="
    echo "FileName",ModifiedDate","Size","CreationDate"
    for /R %%I in (*) do (
        setlocal
        for /f "skip=5 tokens=1-3" %%J in ('dir /T:C "%%~fI"') do (
            if not defined created (
                set "created=1"
                echo "%%~fI","%%~tI","%%~zI","%%J %%K %%L"
            )
        )
        endlocal
    )
)

Or you could instead use a PowerShell one liner:

powershell -noprofile "gci -recurse | select FullName,CreationTime,LastWriteTime,Length | export-csv FileList.csv"

You could easily add Name, Directory, BaseName, Extension, and other columns supported by file objects to your CSV as well, if you wish.

Upvotes: 0

Related Questions