How to find file and folder size using PowerShell

We can use the PowerShell cmdlet Get-Item to get file information including size of a file, we can also the the same command to get folder or directory information but it will return the size of folder as folder is determined by size of all the files that are inside the particular directory.

Find file size

The below command returns the size of the given file as bytes.

$file = 'C:\SamplesTest.csv'
$size=(Get-Item $file).length
Write-Host "Size(Bytes): "$size -ForegroundColor Green

Get file size as KB, MB and GB

We can use the function [System.Math]::Round to convert the byte value to desired unit like KB, MB and GB.

$file = 'C:\SamplesTestVideo.mp4'
$size = (Get-Item $file).length
$sizeKB = [System.Math]::Round((($size)/1KB),2)
$sizeMB = [System.Math]::Round((($size)/1MB),2) 
$sizeGB = [System.Math]::Round((($size)/1GB),2)
Write-Host "Size(KB): "$sizeKB -ForegroundColor Green
Write-Host "Size(MB): "$sizeMB -ForegroundColor Green
Write-Host "Size(GB): "$sizeGB -ForegroundColor Green

Find folder size

You can’t directly find the size of a directory, but you can indirectly determine the size of a folder by getting files using the cmdlets Get-ChildItem and Measure-Object.

$folderInfo = Get-ChildItem C:Scripts | Measure-Object -Property Length -Sum
$filesCount = $folderInfo.Count
$folderSize = $folderInfo.Sum
$folderSizeMB = [System.Math]::Round((($folderSize)/1MB),2) 
Write-Host "Folder Size(MB): "$folderSizeMB  "Total Files: "$filesCount -ForegroundColor Green

Note: The above command calculate folder size only using first level files , it will not include the nested folder files.

Find entire folder size with recursively

To find actual directory size we need to query the Get-ChildItem with -Recurse parameter to et nested level of folder files.

$folderInfo = Get-ChildItem C:Scripts -Recurse | Measure-Object -Property Length -Sum
$allfilesCount = $folderInfo.Count
$folderSize = $folderInfo.Sum
$folderSizeMB = [System.Math]::Round((($folderSize)/1MB),2) 
$folderSizeGB = [System.Math]::Round((($folderSize)/1GB),2) 
Write-Host "Folder Size(MB): "$folderSizeMB  "Total Files: "$filesCount -ForegroundColor Green
Write-Host "Folder Size(GB): "$folderSizeGB -ForegroundColor Green
Advertisement

Leave a Comment