Finding Most Recent File by name

Hello All,

I"m completely new to Powershell.

Requirement: I need to return the most recent(newest) file from a directory. This is part of an ETL process. The file names are all YYYYmmddHHmmSS. However, it could be the case that there may be other files in this folder, so I’d like to only return files that have names that fit the pattern above. For example, 20230224010358.

I chose not to go with a file property like LastWriteTime just in case a file was edited by mistake or something. So I am relying on the file names to determine date and order instead.

I’ve come up with the below solution. It works. I’m just looking for some feedback. Is there a better way to do it? Is there anything wrong with the way I’m doing it? Is there a way to do it without using the regex pattern?

Get-Childitem -Path C:\Files\Archive -Directory -Name
 | where-Object {($_.PSChildName).length -eq 14 -and ($_ -match "^[\d\.]+$")}
 | Sort-Object
 | Select-Object -first 1

Welcome to the forum. :wave:t4:

If the file names consist exclusively of 14 numbers with a trailing period you could shorten the filter like this:

Where-Object {$_.BaseName -match '^\d{14}\.$'}

And while it works for PowerShell version 7.x it is best practice to have the pipe symbol actually at the end of a line right before the line break. :wink:


I just noticed now …

If that’s the condition you won’t get the desired result with

The parameter -Directory limits the output to folders - not files. :wink:

Here’s how I would do it:

Get-Childitem -Path C:\Files\Archive -File |
Where-Object { $_.BaseName -match '^\d14\.$' } |
Sort-Object -Property BaseName |
Select-Object -First 1
1 Like