[powershell] Powershell Get-ChildItem most recent file in directory

We produce files with date in the name. (* below is the wildcard for the date) I want to grab the last file and the folder that contains the file also has a date(month only) in its title.

I am using PowerShell and I am scheduling it to run each day. Here is the script so far:

  $LastFile = *_DailyFile
  $compareDate = (Get-Date).AddDays(-1)
  $LastFileCaptured = Get-ChildItem -Recurse | Where-Object {$LastFile.LastWriteTime        
         -ge $compareDate}

This question is related to powershell

The answer is


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}


You could try to sort descending "sort LastWriteTime -Descending" and then "select -first 1." Not sure which one is faster


Yes I think this would be quicker.

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