Search code examples
batch-filefor-loopfile-properties

Batch: search for files with certain extension, owner, fullpath and last write access and output in CSV


I'm trying to create a CSV with fullpath\filename, file owner and last write access (modification date) of all txt and html files from all hard drives of a data server.

Here's what I got so far:

set pgm=%~n0
set log=%~dpn0.log
set host=%COMPUTERNAME%
set csv=%host%.csv
set dir=D:\BME

if not exist "%csv%" type nul>"%csv%"
    for /f "delims=;" %%a in ('dir /b/s %dir%\*.txt, %dir%\*.html') do (
    >>%csv% echo "%%a"
)

That outputs the path + filename of all found txt and html files of a certain folder in a CSV. I tried this command to get the hard drives:

wmic logicaldisk where drivetype=3 get caption

But I can't get my head around how to store that in a variable or file and loop through it and also retrieve the owner and last modification date and put it into a new column of the csv file.


Solution

  • I can't get my head around how to store that in a variable

    Use the following batch file.

    GetDrives.cmd:

    @echo off
    setlocal enabledelayedexpansion
    rem skip=1 to remove the header
    rem findstr to remove blank lines
    for /f "skip=1" %%d in ('wmic logicaldisk where drivetype^=3 get caption ^| findstr /r /v "^$"') do (
      set _drive=%%d
      echo !_drive!
      )
    endlocal
    

    Notes:

    • Be careful when using drivetype=3 as I have a removable drive of type 3. In the below output C: is a fixed hard disk and F: is a removable external USB drive.
    • Replace echo !_drive! as appropriate with a modified version of your existing code.

    Example Output:

    F:\test>GetDrives
    C:
    F:
    
    F:\test>
    

    Further Reading