1

I want to get total file count and count of files newer than a specific date without having to do 2 separate calls. Is there a way do get both of these counts in 1 call?

Inefficient Way:

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"
Doug Punchak
  • 130
  • 3
  • 11

1 Answers1

2

If I understand correctly, you only need to make the call to Get-ChildItem only once, then filter based on this collection to get the second count ($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'

It's also worth noting that, since the collection ($files) is already in memory, the .Where method is more efficient than Where-Object cmdlet for filtering.

If you need something faster than the .Where filtering technique displayed above:

$ActiveCount = 0
foreach($file in $files) {
    if($file.LastWriteTime -gt $compareDate) {
        $ActiveCount++
    }
}
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
  • Thank you! Is this the fastest and most efficient way to get the counts? I have multiple locations to run this against with millions of files in some. – Doug Punchak May 24 '22 at 16:30
  • @DougPunchak the fastest way of filtering the collection `$files` or the fastest way of enumerating all files? – Santiago Squarzon May 24 '22 at 16:47
  • I guess both but probably enumerating all of the files is what will take the longest. – Doug Punchak May 24 '22 at 16:58
  • @DougPunchak the fastest way would be using .NET API calls to `IO.Directoy` tho that's a matter of a new question not the one being asked. I have some examples if you want to give it a try https://stackoverflow.com/questions/72193074/powershell-slowness-in-get-childitem-directory-recurse-when-there-are-lots // https://stackoverflow.com/questions/71634797/how-to-exclude-folder-from-recursive-get-childpath/71635204 // https://stackoverflow.com/questions/70900685/get-childitem-improve-memory-usage-and-performance/ – Santiago Squarzon May 24 '22 at 17:08