How to Get Last Modified Files in Current Directory

Problem

In this blog post, we will walk through how to get the latest modified files in current directory.

In this context, our directory will look as follows:

scripts-directory-display scripts-export-subdirectory-display

It contains various files and one subfolder named Export. It can be seen that script01.ps1 and script02.ps1 are two latest files that we should find.

Solution

To solve this problem, we must use LastWriteTime property that denotes Date modified of a file.

Having known this property, we can chain several commands that will traverse and recurse the directory to find the latest modified files.

However in this solution, after traversing, it will group the object based on LastWriteTime property because there can be more than one files that have the same modifed time. Many examples in other sources do not use grouping to get the result which is not accurate.

The grouping is done in ascending order based on the key which means the last modified files will be in the last group as follows:


Get-ChildItem -Path 'C:\Scripts' -File -Recurse 
| Group-Object LastWriteTime 

As you can see in below output, the latest modified files are in the last group.

group-object-key-lastwritetime

Therefore, we need to select the last group, then we use -ExpandProperty or -Expand to expand or enumerate the group.

The final script is as follows:


Get-ChildItem -Path 'C:\Scripts' -File -Recurse 
| Group-Object LastWriteTime 
| Select-Object Group -Last 1 
| Select-Object -ExpandProperty Group

Below is the result:

expand-group-object-based-on-lastwritetime

Conclusion

In order to get last modified files in current or specific directory, we must use LastWriteTime property that denotes Date modified of a file. Then, we can design script that will recurse the directory to find the modified files.