Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get N files in a directory order by last modified date?

I want to search for one or few files with latest modified date in a big directory. Trying some PowerShell code but it does not work well for me.

Get-ChildItem 'D:\Temp' | Sort-Object LastWriteTime 

I know that I can use -Recurse to search in all directories. But how to:

  • Limit just some files

  • Order in descending mode

  • Do not list directory

Thanks for your help!

like image 798
fred Avatar asked Dec 01 '16 07:12

fred


People also ask

How do I sort files by last modified?

Open File Explorer and navigate to the location where your files are stored. Sort files by Date Modified (Recent files first). Hold Shift key and click on the Name column. This will bring folders at the top with files sorted with Date Modified.

What command allows you to list files sorted by when they were last modified?

The 'ls' command lists all files and folders in a directory at the command line, but by default ls returns a list in alphabetical order. With a simple command flag, you can have ls sort by date instead, showing the most recently modified items at the top of the ls command results.

How do I print the last modified time of a directory?

Using the stat command, we can also control the output by the -c FORMAT option. There are two formats to display the mtime: %y – displays time of last data modification in a human-readable format. %Y – displays time of last data modification in number of seconds since Epoch.

Which command is used to obtain a list of all files by modification time?

ls command ls – Listing contents of directory, this utility can list the files and directories and can even list all the status information about them including: date and time of modification or access, permissions, size, owner, group etc.


1 Answers

  • Limit just some files => pipe to Select-Object -first 10
  • Order in descending mode => pipe to Sort-Object LastWriteTime -Descending
  • Do not list directory => pipe to Where-Object { -not $_.PsIsContainer }

So to combine them together, here an example which reads all files from D:\Temp, sort them by LastWriteTime descending and select only the first 10:

Get-ChildItem -Force -Recurse -File -Path "C:\Users" -ErrorAction SilentlyContinue | Where-Object { $_.CreationTime.Date -lt (Get-Date).Date } | Sort CreationTime -Descending | Select-Object -First 10 CreationTime,FullName | Format-Table -Wrap  
like image 136
Martin Brandl Avatar answered Oct 03 '22 03:10

Martin Brandl