Poweshell File and Folder Size Function
Have you ever wanted to know the size of a folder using Powershell? Of course! Sure, you can get the size of a file using the length property but what about folders?
This is a function that uses .NET objects to calculate the size of a folder. You can use it for files too.
function Get-Size{
param( $path )
if( test-path $path -pathtype container )
{
$size = _get-dirsize $path
}
else
{
$size = get-item $path
$size = $size.length
}
get-item $path | select-object Name, @{name="Size (MB)";expression={[Math]::Round( ($size / 1MB), 2 )}}, fullname, @{name="Size";expression={$size}} | format-table
}
function _Get-DirSize{
param( $folder )
$folder = resolve-path $folder
$d = New-Object system.IO.DirectoryInfo $folder
[long] $Size = 0;
# Add file sizes.
$fis = $d.GetFiles();
foreach ($fi in $fis){
$size += $fi.Length;
}
# Add subdirectory sizes recursively.
$dis = $d.GetDirectories()
foreach ($di in $dis) {
$Size += _Get-DirSize($di.fullname)
}
return $size
}
This is a function that uses .NET objects to calculate the size of a folder. You can use it for files too.
function Get-Size{
param( $path )
if( test-path $path -pathtype container )
{
$size = _get-dirsize $path
}
else
{
$size = get-item $path
$size = $size.length
}
get-item $path | select-object Name, @{name="Size (MB)";expression={[Math]::Round( ($size / 1MB), 2 )}}, fullname, @{name="Size";expression={$size}} | format-table
}
function _Get-DirSize{
param( $folder )
$folder = resolve-path $folder
$d = New-Object system.IO.DirectoryInfo $folder
[long] $Size = 0;
# Add file sizes.
$fis = $d.GetFiles();
foreach ($fi in $fis){
$size += $fi.Length;
}
# Add subdirectory sizes recursively.
$dis = $d.GetDirectories()
foreach ($di in $dis) {
$Size += _Get-DirSize($di.fullname)
}
return $size
}