Search by date using command line

落爺英雄遲暮 提交于 2019-12-18 12:56:19

问题


Is there any way to search for files in a directory based on date? I want to find all files with created date greater than a specific date, is it possible to do it with dir command?


回答1:


dir by itself can not filter by date, but you can parse the output of dir using for command. If in your country dir prints the date in YMD format, then you only need to compare it with given date. If the order of date parts is different, then you have to use another for command to parse the date and change it to YMD. This will display a list of files modified after 5th Februrary.

@Echo Off

for /f "usebackq tokens=1,4 skip=5" %%A in (`dir /-c`) do (
  if %%A GTR 2012-02-05 echo %%A %%B
)

if does standard string comparison, so at the end you can get additional line if summary line passes the comparison. To avoid it, you can use if %%A GTR 2012-02-05 if exist %%B echo %%A %%B

EDIT: There is even better approach which avoids parsing of dir output and also allows searching by time, not only by date:

@Echo Off

for /r %%A in (*) do (
  if "%%~tA" GTR "2012-02-05 00:00" echo %%~tA %%A
)



回答2:


Just discovered the forfiles command.

forfiles /s /m *.log /d -7 /c "cmd /c echo @path"

Will list all the log files modified more than seven days old, in all subdirectories, though it does not appear to look at the create date. It does support specifying a specific date.

See forfiles /? for more info.




回答3:


Well you cant as far as i know, but this sort of think will work, but still really useless unless you have a short date range ;)

for /R %a in (01 02 03 04 05) do dir | find "02/%a/2012"



回答4:


an easier way for me is something like

dir /s *.xlsx | find "07/14/2016"



回答5:


This is easy to do with PowerShell. I know that your question was about cmd, but PS is included in windows 7 and later. It can also be installed on XP and Vista.

Use the Get-ChildItem command (aliased as dir) to get all files. Pipe the output to the Where-Object command (aliased as ?) to return files where the date is greater then (-gt) a specific date.

For Powershell 2.0 (default on Windows 7), you must use a scriptblock:

dir -file | ? {$_.LastWriteTimeUtc -gt ([datetime]"2013-05-01")}

For Powershell 3.0 (default on Windows 8) and up you can use this simpler syntax instead:

dir -file | ? LastWriteTimeUtc -gt ([datetime]"2013-05-01")

The dir -file command returns a collection of System.IO.FileInfo objects. This file object has many properties that you can use for complex filtering (file size, creation date, etc.). See MSDN for documentation.



来源:https://stackoverflow.com/questions/9234207/search-by-date-using-command-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!