How do I find the newest file in a directory using a PowerShell script?
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
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
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