Powershell Get-ChildItem most recent file in directory

Yes I think this would be quicker.

Get-ChildItem $folder | Sort-Object -Descending -Property LastWriteTime -Top 1 

If you want the latest file in the directory and you are using only the LastWriteTime to determine the latest file, you can do something like below:

gci path | sort LastWriteTime | select -last 1

On the other hand, if you want to only rely on the names that have the dates in them, you should be able to something similar

gci path | select -last 1

Also, if there are directories in the directory, you might want to add a ?{-not $_.PsIsContainer}


Try:

$latest = (Get-ChildItem -Attributes !Directory | Sort-Object -Descending -Property LastWriteTime | select -First 1)
$latest_filename = $latest.Name 

Explanation:

PS C:\Temp> Get-ChildItem -Attributes !Directory *.txt | Sort-Object -Descending -Property LastWriteTime | select -First 1


    Directory: C:\Temp


Mode                LastWriteTime         Length Name                                                                                
----                -------------         ------ ----                                                                                
-a----         5/7/2021   5:51 PM           1802 Prison_Mike_autobiography.txt                    
  • Get-ChildItem -Attributes !Directory *.txt or Get-ChildItem or gci : Gets list of files ONLY in current directory. We can give a file extension filter too as needed like *.txt. Reference: gci, Get-ChildItem
  • Sort-Object -Descending -Property LastWriteTime : Sort files by LastWriteTime (modified time) in descending order. Reference
  • select -First 1 : Gets the first/top record. Reference Select-Object / select

Getting file metadata

PS C:\Temp> $latest.Name
Prison_Mike_autobiography.txt

PS C:\Temp> $latest.DirectoryName
C:\Temp

PS C:\Temp> $latest.FullName
C:\Temp\Prison_Mike_autobiography.txt

PS C:\Temp> $latest.CreationTime
Friday, May 7, 2021 5:51:19 PM


PS C:\Temp> $latest.Mode
-a----

Tags:

Powershell