How do I find the newest file in a directory using a PowerShell script?

后端 未结 5 1516
迷失自我
迷失自我 2020-12-05 04:40

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         


        
相关标签:
5条回答
  • 2020-12-05 04:58

    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
    
    0 讨论(0)
  • 2020-12-05 04:59

    I use this to get last updated files. Easy to write.

    ls | sort LastWriteTime
    
    0 讨论(0)
  • 2020-12-05 05:05

    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
    
    0 讨论(0)
  • 2020-12-05 05:07

    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
    
    0 讨论(0)
  • 2020-12-05 05:13

    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
    
    0 讨论(0)
提交回复
热议问题