Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get size of folder
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
You can’t perform that action at this time.