Find the most recently modified file with PowerShell

  • Published: 2026.11.22
  • Updated: 2026.11.22
  • Windows

When several logs have similar names, the filename alone may not tell you which one was modified most recently. PowerShell can sort file objects by LastWriteTime and return just the first result.

These examples use the Windows file system in Windows PowerShell 5.1 and PowerShell 7. Replace .\logs[demo] with your folder. -LiteralPath keeps the square brackets in the example folder name literal.


Find the most recently modified matching file

Get-ChildItem -LiteralPath '.\logs[demo]' -File -Filter '*.log' -ErrorAction Stop |
    Sort-Object LastWriteTime -Descending |
    Select-Object -First 1 -Property Name, LastWriteTime

-File selects files, and -Filter '*.log' limits the names. Sort-Object LastWriteTime -Descending puts the most recently modified file first; Select-Object -First 1 keeps that file and displays its name and timestamp.

In a sample folder with old.log modified on November 1 at 09:00 and new.log modified on November 2 at 09:00, the result was new.log. The displayed date format depends on the session’s culture.

Include subfolders and keep more results

Get-ChildItem -LiteralPath '.\logs[demo]' -File -Filter '*.log' -Recurse -ErrorAction Stop |
    Sort-Object LastWriteTime -Descending |
    Select-Object -First 2 -Property Name, LastWriteTime

The sample’s archive subfolder contained archived.log, modified on November 3 at 09:00. With -Recurse, the first two results were archived.log followed by new.log. Change -First 2 to the maximum number of files you need. The result can contain fewer files when fewer match.

Choose a secondary order for equal timestamps

If two files have the same modified time, you can sort that group by name:

Get-ChildItem -LiteralPath '.\logs[demo]' -File -Filter '*.log' -ErrorAction Stop |
    Sort-Object @{Expression='LastWriteTime';Descending=$true}, Name |
    Select-Object -First 1 -Property Name, LastWriteTime

This applies descending order to LastWriteTime and the default ascending order to Name. In the sample, setting old.log and new.log to the same time still selected new.log first by name.

Check the scan and timestamp you are using

The examples use -ErrorAction Stop on Get-ChildItem, so a path or access error stops the pipeline. Resolve any error before using the selected file. An existing folder with no matching files returns no selected file.

LastWriteTime is the file’s last modified time. To inspect a known file’s timestamp and size, see reading file properties with Get-Item. To adjust extensions, hidden-file selection or listing scope, see filtering a file listing with Get-ChildItem.

References

このブラウザからの自分のアクセスを解析から除外できます。