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

This works for me:

PS> dir | Sort-Object LastAccessTime 

Its almost the same as the bash command:

$ ls -ltr

To Filter Directories:

PS> dir | Sort-Object LastAccessTime | Out-String -Stream | Select-String -NotMatch "^d"

(Personally, I think Microsoft should merge "out-string -stream" and "sls" to make a new command called "out-grep", so that powershell works more normally for bash users without messing around with customizing your shell. Who wants to type all of that junk just to grep a command output?)

The bash command would be:

$ ls -ltr | egrep -v "^d"

  • 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