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"
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++
}
}