Created
October 7, 2019 11:03
-
-
Save AshFlaw/319ce2074e6cfeaa06d89d37d0b3ef13 to your computer and use it in GitHub Desktop.
Get size of 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
Function Get-FolderSize { | |
[cmdletbinding()] | |
param | |
( | |
[Parameter(Mandatory = $false)] | |
[Alias('Path')] | |
[String[]] | |
$BasePath = 'C:\', | |
[Parameter(Mandatory = $false)] | |
[Alias('User')] | |
[String[]] | |
$FolderName = 'all', | |
[Parameter()] | |
[String[]] | |
$OmitFolders, | |
[Parameter()] | |
[Switch] | |
$AddTotal | |
) | |
if ($folderName -eq 'all') {$allFolders = Get-ChildItem $BasePath -Directory -Force | Where-Object {$_.FullName -notin $OmitFolders}} | |
else {$allFolders = Get-ChildItem $basePath -Directory -Force | Where-Object {($_.BaseName -like $FolderName) -and ($_.FullName -notin $OmitFolders)}} | |
[System.Collections.ArrayList]$folderList = @() | |
ForEach ($folder in $allFolders) { | |
$fullPath = $null | |
$folderObject = $null | |
$folderSize = $null | |
$folderSizeInMB = $null | |
$folderSizeInGB = $null | |
$folderBaseName = $null | |
$fullPath = $folder.FullName | |
$folderBaseName = $folder.BaseName | |
$folderSize = Get-Childitem -Path $fullPath -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue | |
$folderSizeInMB = "{0:N2}" -f ($folderSize.Sum / 1MB) | |
$folderSizeInGB = "{0:N2}" -f ($folderSize.Sum / 1GB) | |
$folderObject = [PSCustomObject]@{ | |
FolderName = $folderBaseName | |
'Size(Bytes)' = $folderSize.Sum | |
'Size(MB)' = $folderSizeInMB | |
'Size(GB)' = $folderSizeInGB | |
} | |
$folderList.Add($folderObject) | Out-Null | |
} | |
if ($AddTotal) { | |
$grandTotal = $null | |
if ($folderList.Count -gt 1) { | |
$folderList | ForEach-Object {$grandTotal += $_.'Size(Bytes)'} | |
$totalFolderSizeInMB = "{0:N2}" -f ($grandTotal / 1MB) | |
$totalFolderSizeInGB = "{0:N2}" -f ($grandTotal / 1GB) | |
$folderObject = [PSCustomObject]@{ | |
FolderName = 'GrandTotal' | |
'Size(Bytes)' = $grandTotal | |
'Size(MB)' = $totalFolderSizeInMB | |
'Size(GB)' = $totalFolderSizeInGB | |
} | |
$folderList.Add($folderObject) | Out-Null | |
} | |
} | |
Return $folderList | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment