Created
October 23, 2023 10:16
-
-
Save scottglew/ad5a19841bbf6399a6189a943ede213b to your computer and use it in GitHub Desktop.
Recursively searches all sub-folders in the current location and outputs a csv file listing all file and folder sizes, and the number of files in each folder.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Get the current directory | |
$currentDir = Get-Location | |
# Prompt the user for a filename to save the results | |
$filename = Read-Host -Prompt "Enter the filename to save the results (e.g., output.csv)" | |
# Use an ArrayList for more efficient data collection | |
$results = New-Object System.Collections.ArrayList | |
# Hashtable to store folder sizes and file counts | |
$folderData = @{} | |
# Fetch all items recursively | |
$items = Get-ChildItem -Path $currentDir -Recurse | |
$totalItems = $items.Count | |
$currentItemNumber = 0 | |
foreach ($item in $items) { | |
$currentItemNumber++ | |
Write-Progress -PercentComplete (($currentItemNumber / $totalItems) * 100) -Status "Processing items" -Activity "Processed $currentItemNumber of $totalItems" | |
if ($item -is [System.IO.FileInfo]) { | |
# Update folder data in the hashtable | |
$parentDir = $item.DirectoryName | |
if (-not $folderData.ContainsKey($parentDir)) { | |
$folderData[$parentDir] = @{ | |
'Size' = 0; | |
'FileCount' = 0; | |
} | |
} | |
$folderData[$parentDir]['Size'] += $item.Length | |
$folderData[$parentDir]['FileCount'] += 1 | |
# Add file data to results | |
$null = $results.Add([PSCustomObject]@{ | |
'Path' = $item.FullName | |
'Size (Bytes)' = $item.Length | |
'File Count' = $null | |
'Type' = 'File' | |
}) | |
} | |
} | |
foreach ($key in $folderData.Keys) { | |
$null = $results.Add([PSCustomObject]@{ | |
'Path' = $key | |
'Size (Bytes)' = $folderData[$key]['Size'] | |
'File Count' = $folderData[$key]['FileCount'] | |
'Type' = 'Folder' | |
}) | |
} | |
# Save the results to the provided filename | |
$results | Export-Csv -Path $filename -NoTypeInformation | |
Write-Host "Results saved to $filename." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment