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}

Solution 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}

Solution 2:

Yes I think this would be quicker.

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

Solution 3:

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