Powershell Get-ChildItem 目录中最新的文件

我们生产的文件日期的名称。 (* 下面是日期的通配符) 我想抓取最后一个文件和包含该文件的文件夹也有一个日期(仅月)在其标题。

我正在使用 PowerShell,并将其安排为每天运行:

  $LastFile = *_DailyFile
$compareDate = (Get-Date).AddDays(-1)
$LastFileCaptured = Get-ChildItem -Recurse | Where-Object {$LastFile.LastWriteTime
-ge $compareDate}
170227 次浏览

If you want the latest file in the directory and you are using only the LastWriteTime to determine the latest file, you can do something like below:

gci path | sort LastWriteTime | select -last 1

On the other hand, if you want to only rely on the names that have the dates in them, you should be able to something similar

gci path | select -last 1

Also, if there are directories in the directory, you might want to add a ?{-not $_.PsIsContainer}

You could try to sort descending "sort LastWriteTime -Descending" and then "select -first 1." Not sure which one is faster

Yes I think this would be quicker.

Get-ChildItem $folder | Sort-Object -Descending -Property LastWriteTime -Top 1

Try:

$latest = (Get-ChildItem -Attributes !Directory | Sort-Object -Descending -Property LastWriteTime | select -First 1)
$latest_filename = $latest.Name

Explanation:

PS C:\Temp> Get-ChildItem -Attributes !Directory *.txt | Sort-Object -Descending -Property LastWriteTime | select -First 1




Directory: C:\Temp




Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----         5/7/2021   5:51 PM           1802 Prison_Mike_autobiography.txt
  • Get-ChildItem -Attributes !Directory *.txt or Get-ChildItem or gci : Gets list of files ONLY in current directory. We can give a file extension filter too as needed like *.txt. Reference: gci, Get-ChildItem
  • Sort-Object -Descending -Property LastWriteTime : Sort files by LastWriteTime (modified time) in descending order. Reference
  • select -First 1 : Gets the first/top record. Reference Select-Object / select

Getting file metadata

PS C:\Temp> $latest.Name
Prison_Mike_autobiography.txt


PS C:\Temp> $latest.DirectoryName
C:\Temp


PS C:\Temp> $latest.FullName
C:\Temp\Prison_Mike_autobiography.txt


PS C:\Temp> $latest.CreationTime
Friday, May 7, 2021 5:51:19 PM




PS C:\Temp> $latest.Mode
-a----


@manojlds's answer is probably the best for the scenario where you are only interested in files within a root directory:

\path
\file1
\file2
\file3

However, if the files you are interested are part of a tree of files and directories, such as:

\path
\file1
\file2
\dir1
\file3
\dir2
\file4

To find, recursively, the list of the 10 most recently modified files in Windows, you can run:

PS > $Path = pwd # your root directory
PS > $ChildItems = Get-ChildItem $Path -Recurse -File
PS > $ChildItems | Sort-Object LastWriteTime -Descending | Select-Object -First 10 FullName, LastWriteTime