If you want the full file names sorted in chronological order by embedded timestamp (with possibly varying name prefixes), pass a timestamp-extraction expression as a sort criterion.
$Start, $End = (Get-ChildItem *.xlsx |
Sort-Object { ($_.Name -split '[-.]')[-2] }).FullName
Get-ChildItem *.xlsx
gets file-info objects for all files with extension .xlsx
in the current directory ([System.IO.FileInfo]
instances).
Sort-Object
receives a script block ({ ... }
) as a criterion that extracts the timestamp from each input file's name ($_.Name
) by splitting it by -
and .
characters and extracting the second-to-last ([-2]
) resulting token.
(...).FullName
uses member-access enumeration to extract the full names (paths) of the sorted file-info objects.
$Start, $End = ...
is a destructuring assignment that assigns the 2 (chronologically sorted) full file names to individual variables. Note that if there were more than 2 files, $End
would receive all remaining files, as an array.
As an aside:
Given the format of your timestamp strings, you can use them as-is for comparison, because lexical comparison will be equivalent to chronological comparison.
If you wanted to convert the timestamp strings to proper .NET [datetime]
instances, do the following:
$timeStamps = Get-ChildItem *.xlsx | ForEach-Object {
[datetime]::ParseExact(($_.Name -split '[-.]')[-2], 'yyyyMMdd_HHmmss', $null)
}