List latest files from all directories in a given path using PowerShell
PowerShell is mostly used to execute scripts. But as everyone knows, PowerShell is also great for using interactive. For that, the best choice is the PowerShell Integrated Scripting Environment (PowerShell_ise).
But what brought me to this idea? I just want to know, how are the activities on certain directories by listing all the new files. To handle all with files, two of the PowerShell CmdLets are Get-Item
and
Here it is :
# List the newest file from each directory in path Get-ChildItem -Path <Drive & Path where to start> -Recurse | group directory | foreach {$_.group | sort LastWriteTime -Descending | select -First 1}
When you will view over the result, you will maybe recognize, that there are files already years old. That means already for years, there are no new files or no activity in that folder. For that, it’s possible to filter the returned files with a date. When you dont expect hundreds of new files, you can remove the | select -First 1
at the end of the statement or higher the value to maybe 10. Have a look on that:
# List the newest file from each directory in path Get-ChildItem -Path <Drive & Path where to start> -Recurse | group directory | foreach {$_.group | sort LastWriteTime -Descending | where LastWriteTime -GE (Date).AddDays(-7) | select -First 5}
When the result is spawned over many folders, then maybe the result is better returned as a complete list of files with the full name. Have a look at this:
# List the newest file from each directory in path Get-ChildItem -Path <Drive & Path where to start> -Recurse | group directory | foreach {$_.group | where LastWriteTime -GE (Date).AddDays(-7) | sort LastWriteTime -Descending | select FullName, LastWriteTime -First 5}
The samples above works fine in PowerShell 5.1. Just now I found out that there are problems in earlier Versions of PowerShell. If you use a Version before PowerShell 5.1, you have to change the samples to:
# List the newest file from each directory in path Get-ChildItem -Path <Drive & Path where to start> -Recurse | group directory | foreach {$_.group | where {$_.LastWriteTime -GE (Date).AddDays(-7)} | sort LastWriteTime -Descending | select FullName, LastWriteTime -First 5}