If, for example, I have a directory which contains the following files:
Test-20120626-1023.txt
Test-20120626-0710.txt
Test-20120626-2202.txt
Test-20120626-19
If the name is the equivalent creation time of the file property CreationTime
, you can easily use:
$a = Dir | Sort CreationTime -Descending | Select Name -First 1
then
$a.name
contains the name file.
I think it also works like this if name always have the same format (date and time with padding 0, for example, 20120102-0001):
$a = Dir | Sort Name -Descending | Select Name -First 1
I use this to get last updated files. Easy to write.
ls | sort LastWriteTime
If you're working with a large number of files, I'd suggest using the -Filter
parameter as the execution time will be greatly reduced.
Based on the example James provided, here is how it would be used;
$dir = "C:\test_code"
$filter="*.txt"
$latest = Get-ChildItem -Path $dir -Filter $filter | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.name
If, for some reason, the files creation date is different than the one stamped in the file name then you can parse the file name into a datetime object and sort by expression:
$file = Get-ChildItem |
Sort-Object { [DateTime]::ParseExact($_.BaseName,'\Te\s\t\-yyyyMMdd\-HHmm',$null) } |
Select-Object -Last 1
You could try something like this:
$dir = "C:\test_code"
$latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.name