PowerShell 总文件数和比某个日期更新的文件数

PowerShell Total File Count And Count Files Newer Than A Date

我想获得总文件数和比特定日期更新的文件数,而无需执行 2 个单独的调用。有没有办法在一次调用中获得这两个计数?

低效的方式:

cls
$compareDate = (Get-Date).AddDays(-365) 
$FileShare = "C:\Folder\Subfolder"
$TotalCount = (Get-ChildItem -File  -Recurse $FileShare | Measure-Object).Count
$ActiveCount = (Get-ChildItem -File -Recurse $FileShare | Where-Object { $_.LastWriteTime -gt $compareDate}).Count
$Percentage = ($ActiveCount/$TotalCount)*100
Write-Host $ActiveCount/$TotalCount " is " $Percentage.ToString("#.##") "% Active"

如果我没理解错的话,你只需要调用一次Get-ChildItem,然后根据这个集合过滤得到第二个计数($ActiveCount):

$compareDate = (Get-Date).AddDays(-365)
$files = Get-ChildItem -File -Recurse "C:\Folder\SubFolder"
$totalCount  = $files.Count
$ActiveCount = $files.Where{ $_.LastWriteTime -gt $compareDate }.Count
'Thing is ' + ($ActiveCount / $totalCount).ToString('P2') + ' Active'

还值得注意的是,由于集合 ($files) 已经在内存中,因此 .Where method is more efficient than Where-Object cmdlet 用于过滤。

如果您需要比上面显示的 .Where 过滤技术更快的东西:

$ActiveCount = 0
foreach($file in $files) {
    if($file.LastWriteTime -gt $compareDate) {
        $ActiveCount++
    }
}