John Evans Solachuk
John Evans Solachuk

Reputation: 2085

How to write batch script to find files before or after a certain date time?

I am currently using this script to find files after a certain date.

forfiles /P directory /S /D +%day%/%month%/%year%

Problem is, I cannot find ways to make it time-specific. E.g., I want to find files after 23/03/2017 17:30 (5:30pm).

Is there a batch script that allows me to find files before/after a certain date time?

If possible, I would not like to use forfiles due to its date parameter format being region-specific.

Upvotes: 0

Views: 1135

Answers (1)

JosefZ
JosefZ

Reputation: 30113

For region/locale independent solution, use next PowerShell code snippet:

$closeTime = Get-Date -Year 2017 -Month 3 -Day 18 -Hour 17 -Minute 30
Get-ChildItem D:\bat\so -File | 
    Where-Object { $_.LastWriteTime -ge $closeTime } |
        ForEach-Object {
            # do something with a file
            '{0} {1}' -f $_.LastWriteTime, $_.FullName
        }

Edit: unfortunately, my first attempt is wrong as it simulates next PowerShell code snippet (displays only files after 17:30 in each day not after a specified day, 17:30):

Get-ChildItem D:\bat\so -File | 
    Where-Object { $_.LastWriteTime -ge $(Get-Date -Year 2017 -Month 3 -Day 18) } | 
        Where-Object {$_.LastWriteTime.Hour -ge 17 -and $_.LastWriteTime.Minute -ge 30} | 
            ForEach-Object {
                 # do something with a file
                '{0} {1}' -f $_.LastWriteTime, $_.FullName
            }

FORFILES.exe does not offer such a possibility. However, you can check time using IF to conditionally perform a command on each file as follows:

==> FORFILES /P SO /D +18/03/2017 /C "cmd /c if "@ftime" GEQ "17:30:00" (echo @fdate @ftime GEQ @path) else (echo @fdate @ftime LSS @path)"

20/03/2017 19:59:05 GEQ "d:\bat\SO\42911145.bat"
21/03/2017 08:52:49 LSS "d:\bat\SO\42918825.bat"
22/03/2017 13:44:52 LSS "d:\bat\SO\numberedFiles.bat"

==>

Omit else branch if unnecessary:

==> FORFILES /P SO /D +18/03/2017 /C "cmd /c if "@ftime" GEQ "17:30:00" echo @fdate @ftime GEQ @path"

20/03/2017 19:59:05 GEQ "d:\bat\SO\42911145.bat"

==>

Read TIME - Display or set the system time article as well for more info about regional specific time format.

Upvotes: 1

Related Questions