Windows размер папок powershell

С помощью PowerShell вы можете определить точный размер определенного каталога в Windows (с учетом всех вложенных директорий). Это позволит узнать размер каталог без использования сторонних утилит, таких как TreeSize или WinDirStat. Кроме того, PowerShell позволяет более гибко отфильтровать файлы по типам или размерам, которые нужно учитывать при расчете размера папки.

Для получения размеров файлов в каталогах используются следующие командлеты PowerShell:

  • Get-ChildItem (алиас
    gci
    ) — позволяет получить список файлов в директории (включая вложенные объекты)
  • Measure-Object (алиас
    measure
    ) – складывает размеры всех файлов для получения суммарного размера директории

Например, чтобы получить полный размер директории F:\ISO в Гб, выполните команду:

(Get-ChildItem F:\ISO -force -Recurse -ErrorAction SilentlyContinue| measure Length -sum).sum / 1Gb

Рассмотрим используемые параметры:

  • -Force
    — учитывать скрытые и системные файлы
  • -Recure
    — получать список файлов во вложенных директориях
  • -ErrorAction SilentlyContinue
    – игонрировать объекты, к которым у текущего пользователя нет доступа
  • -measure Length -sum
    – сложить размеры всех файлов (свойство Length)
  • .sum/ 1Gb
    – вывести только суммарный размер в Гб

В данном примере размер директории около 37 Гб (без учета NTFS сжатия). Чтобы округлить результаты до двух символов после запятой, выполните команду:

"{0:N2} GB" -f ((Get-ChildItem F:\ISO -force -Recurse -ErrorAction SilentlyContinue| measure Length -sum).sum / 1Gb)

Узнать размер директории с помощью PowerShell команды

С помощью PowerShell можно получить суммарный размер всех файлов определенного типа в директории. Например, чтобы узнать сколько места занято ISO файлами, добавьте параметр
*.iso
:

"{0:N2} GB" -f ((Get-ChildItem  F:\ISO *.iso -force -Recurse -ErrorAction SilentlyContinue| measure Length -sum).sum / 1Gb)

Суммартный размер файлов определенного типа в папке

Можно использовать другие фильтры для выбора файлов, которые учитываются при расчете размера директории. Например, вы можете получить размер файлов, созданных за 2023 год

(gci -force f:\iso –Recurse -ErrorAction SilentlyContinue | ? {$_.CreationTime -gt ‘1/1/23’ -AND $_.CreationTime -lt ‘12/31/23’}| measure Length -sum).sum / 1Gb

Указанная выше PowerShell команда при подсчете размера файлов в каталоге будет выводить неверные данные, если в директории есть символические или жесткие ссылки. Например, в каталоге C:\Windows находится много жестких ссылок на файлы в хранилище компонентов WinSxS. В результате такие файлы могут быть посчитаны несколько раз. Чтобы не учитывать в результатах жесткие ссылки, используйте следующую команду (выполняется довольно долго):

"{0:N2} GB" -f ((gci –force C:\windows –Recurse -ErrorAction SilentlyContinue | Where-Object { $_.LinkType -notmatch "HardLink" }| measure Length -s).sum / 1Gb)

размер каталога windows без учетка жестких ссылок в winsxs

Вывести размер всех вложенных папок первого уровня в директории и количество файлов в каждой из них (в этом примере скрипт выведет размер всех профилей пользователей в C:\Users):

$targetfolder='C:\Users'
$dataColl = @()
gci -force $targetfolder -ErrorAction SilentlyContinue | ? { $_ -is [io.directoryinfo] } | % {
    $len = 0
    gci -recurse -force $_.fullname -ErrorAction SilentlyContinue | % { $len += $_.length }
    $filesCount = (gci -recurse -force $_.fullname -File -ErrorAction SilentlyContinue | Measure-Object).Count
  $dataObject = New-Object PSObject -Property @{
        Folder = $_.fullname
        SizeGb = ('{0:N3}' -f ($len / 1Gb)) -as [single]
        filesCount=$filesCount
    }
   $dataColl += $dataObject
   }
$dataColl | Out-GridView -Title "Размер вложенных каталогов и количество файлов"

powershell скрипт для получения размер вложенных директорий и количества файлов в них

% — это алиас для цикла foreach-object.

Скрипт выведет графическую таблицу Out-GridView со списком директорий, их размеров и количество файлов в каждой из них. Вы можете отсортировать каталоги в таблице по их размеру. Вы также можете выгрузить результаты в CSV (
|Export-Csv file.csv
) или Excel файл.

You can use PowerShell to calculate the exact size of a specific folder in Windows (recursively, including all subfolders). This way you can quickly find out the size of the directory on disk without using third-party tools such as TreeSize or WinDirStat. In addition, PowerShell gives you more flexibility to filter or exclude files (by type, size, or date) that you need to consider when calculating folder size.

Use the following PowerShell cmdlets to calculate the size of a folder:

  • Get-ChildItem (gci alias) — gets a list of files (with sizes) in a directory (including nested subfolders). Previously, we showed you how to use the Get-ChildItem cmdlet to find the largest files on the disk.
  • Measure-Object (measure alias) – sums the sizes of all files to get the total directory size.

For example, to find the size of the D:\ISO directory in GB, run:

(Get-ChildItem D:\ISO -force -Recurse -ErrorAction SilentlyContinue| measure Length -sum).sum / 1Gb

Parameters used:

  • -Force – include hidden and system files
  • -Recure – get a list of files in subfolders
  • -ErrorAction SilentlyContinue – ignore files and folders the current user is not allowed to access
  • -measure Length -sum – a sum of all file sizes (the Length property)
  • .sum/ 1Gb – show total size in GB

In this example, the directory size is about 37 GB (this PowerShell command ignores NTFS file system compression if it is enabled).

To round the results to two decimal places, use the command:

"{0:N2} GB" -f ((Get-ChildItem D:\ISO -force -Recurse -ErrorAction SilentlyContinue| measure Length -sum).sum / 1Gb)

PowerShell can find the total size of all files of a particular type in a directory. For example, add the *.iso parameter to find out how much space is taken up by ISO files:

"{0:N2} GB" -f ((Get-ChildItem D:\ISO *.iso -force -Recurse -ErrorAction SilentlyContinue| measure Length -sum).sum / 1Gb)

calculate file size in folder with powershell oneliner

You can use other filters to select files to be included in the directory size calculation. For example, to see the size of files in the directory created in 2024:

(gci -force D:\ISO –Recurse -ErrorAction SilentlyContinue | ? {$_.CreationTime -gt '1/1/24’ -AND $_.CreationTime -lt '12/31/24'}| measure Length -sum).sum / 1Gb

If there are symbolic or hard links in the directory, the above PowerShell cmdlet displays an incorrect folder size. For example, the C:\Windows directory contains many hard links to files in the WinSxS folder (Windows Component Store). Such files may be counted several times. Use the following command to ignore hard links:

"{0:N2} GB" -f ((gci –force C:\Windows –Recurse -ErrorAction SilentlyContinue | Where-Object { $_.LinkType -notmatch "HardLink" }| measure Length -s).sum / 1Gb)

Get the sizes of all top-level subfolders in the destination folder and the number of files in each subfolder (in this example, the PowerShell script displays the size of all user profiles in C:\Users):

$targetfolder='C:\Users'
$dataColl = @()
gci -force $targetfolder -ErrorAction SilentlyContinue | ? { $_ -is [io.directoryinfo] } | % {
    $len = 0
    gci -recurse -force $_.fullname -ErrorAction SilentlyContinue | % { $len += $_.length }
    $filesCount = (gci -recurse -force $_.fullname -File -ErrorAction SilentlyContinue | Measure-Object).Count
  $dataObject = New-Object PSObject -Property @{
        Folder = $_.fullname
        SizeGb = ('{0:N3}' -f ($len / 1Gb)) -as [single]
        filesCount=$filesCount
    }
   $dataColl += $dataObject
   }
$dataColl | Out-GridView -Title "Subfolder sizes and number of files"

get subfolder sizes and file count using PowerShell

% is an alias for the foreach-object loop.

The script will display the Out-GridView graphical table listing the directories, their sizes, and how many files they contain. The folders in the table can be sorted by size or number of files in the Out-GridView form. You can also export the results to a CSV  (| Export-Csv folder_size.csv) or to an Excel file.

Summary: Guest blogger, Bill Stewart, discusses a Windows PowerShell function to determine folder size.

Microsoft Scripting Guy, Ed Wilson, is here. Guest blogger today is Bill Stewart. Bill Stewart is a scripting guru and a moderator for the Official Scripting Guys forum.

Here’s Bill…

You have probably asked this question hundreds of times, “How big is that folder?” Of course, the typical GUI way to find out is to right-click the folder in Windows Explorer and open the folder’s properties. As with all things GUI, this does not scale well. For example, what if you need the size for 100 different folders?

If you have worked with Windows PowerShell for any length of time, you know that it provides a pretty comprehensive set of tools. The trick is learning how to combine the tools to get the results you need. In this case, I know that Windows PowerShell can find files (Get-ChildItem), and I know that it can count objects and sum a property on objects. A simple example would be a command like this:

Get-ChildItem | Measure-Object -Sum Length

Get-ChildItem outputs a list of items in the current location (in files and folders, if your current location is in a file system), and Measure-Object uses this list as input and adds together every input object’s Length property (file size). In other words, this command tells you the count and sum of the sizes of all the files in the current directory.

The Measure-Object cmdlet outputs an object with five properties (including Count, Average, and Sum). However, we only care about the Count and Sum properties, so let us refine our command a bit:

Get-ChildItem | Measure-Object -Sum Length | Select-Object Count, Sum

Now we are using Select-Object to select (hence the name) only the two properties we care about. The end result is a new output object that contains only those two properties.

This is good as far as it goes, but I wanted my output object to include the directory’s name. In addition, while we are at it, let us use the names “Files” and “Size” instead of “Count” and “Sum.” To do this, I am going to output a custom object like this:

$directory = Get-Item .

$directory | Get-ChildItem |

  Measure-Object -Sum Length | Select-Object `

    @{Name=”Path”; Expression={$directory.FullName}},

    @{Name=”Files”; Expression={$_.Count}},

    @{Name=”Size”; Expression={$_.Sum}}

I need $directory as a separate variable so I can include it in the output object. In addition, you can see here that I am using Select-Object with a set of hash tables as a shorthand technique for creating a custom output object.

In the following image (Figure 1), you can see the output from all three of the commands.

Image of command output

The output does not look that great, but remember that the presentation is less important than the content: We are outputting objects, not text. Because the output is objects, we can sort, filter, and measure.

To get the output we want (include the path name and change a couple of the property names), the commands can start to get a bit lengthy. So it makes sense to encapsulate the needed code in a script. Get-DirStats.ps1 is the script, and its syntax is as follows:

Get-DirStats [[-Path] <Object>] [-Only] [-Every] [-FormatNumbers] [-Total]

or

Get-DirStats -LiteralPath <String[]> [-Only] [-Every] [-FormatNumbers] [-Total]

As you can see, you can run the script by using two sets of mutually exclusive parameters. Windows PowerShell calls these parameter sets. The parameter sets’ names (Path and LiteralPath) are defined in the statement at the top of the script, and the script’s CmdletBinding attribute specifies that Path is the default parameter set.

The Path parameter supports pipeline input. Also, the Path parameter is defined as being first on the script’s command line, so the Path parameter name itself is optional. The LiteralPath parameter is useful when a directory name contains characters that Windows PowerShell would normally interpret as wildcard characters (the usual culprits are the [ and the ] characters.) The Path and LiteralPath parameters are in different parameter sets, so they’re mutually exclusive.

The Only parameter calculates the directory size only for the named path(s), but not subdirectories (like what is shown in Figure 1). Normally, when we ask about the size of a directory, we’re asking about all of its subdirectories also. If you only care about counting and summing the sizes of the files in a single directory (but not its subdirectories), you can use the Only parameter.

The Every parameter outputs an object for every subdirectory in the path. Without the Every parameter, the script outputs an object for the first level of subdirectories only. The following image shows what I mean.

Image of menu

If we use the following command, the script will output an object for every directory in the left (navigation) pane (if we expand them all, as shown in the previous image).

Get-DirStats -Path C:\Temp -Every

If we omit the Every parameter from this command, the script will only output the directories in the right pane. The script will still get the sizes of subdirectories if you omit the Every parameter; the difference is in the number of output objects.

The FormatNumbers parameter causes the script to output numbers as formatted strings with thousands separators, and the Total parameter outputs a final object after all other output that adds up the total number of files and directories for all output. These parameters are useful when running the script at a Windows PowerShell command prompt; but you shouldn’t use them if you’re going to do something else with the output (such as sorting or filtering) because the numbers will be text (with FormatNumbers) and there will be an extra object (with Total). The following image  shows an example command that uses the  FormatNumbers and Total parameters with US English thousands separators.

Image of command output

Get-DirStats.ps1 supports pipeline input, so it uses the Begin, Process, and End script blocks. The script uses the following lines of code within the Begin script block to detect the current parameter set and whether input is coming from the pipeline:

$ParamSetName = $PSCmdlet.ParameterSetName

if ( $ParamSetName -eq “Path” ) {

  $PipelineInput = ( -not $PSBoundParameters.ContainsKey(“Path”) ) -and ( -not $Path )

}

elseif ( $ParamSetName -eq “LiteralPath” ) {

  $PipelineInput = $false

}

The script uses the $ParamSetName and $PipelineInput variables later in the Process script block. The logic behind the definition of the $PipelineInput variable is thus: “If the Path parameter is not bound (that is, it was not specified on the script’s command line), and the $Path variable is $null, then the input is coming from the pipeline.” Both the $ParamSetName and $PipelineInput variables are used in the script’s Process script block.

The beginning of script’s Process script block has the following code:

if ( $PipelineInput ) {

  $item = $_

}

else {

  if ( $ParamSetName -eq “Path” ) {

    $item = $Path

  }

  elseif ( $ParamSetName -eq “LiteralPath” ) {

    $item = $LiteralPath

  }

}

The $item variable will contain the path that the script will process. Thus, if the script’s input is coming from the pipeline, $item will be the current pipeline object ($_); otherwise, $item will be $Path or $LiteralPath (depending on the current parameter set).

Next, Get-DirStats.ps1 uses the Get-Directory function as shown here:

function Get-Directory {

  param( $item )

  if ( $ParamSetName -eq “Path” ) {

    if ( Test-Path -Path $item -PathType Container ) {

      $item = Get-Item -Path $item -Force

    }

  }

  elseif ( $ParamSetName -eq “LiteralPath” ) {

    if ( Test-Path -LiteralPath $item -PathType Container ) {

      $item = Get-Item -LiteralPath $item -Force

    }

  }

  if ( $item -and ($item -is [System.IO.DirectoryInfo]) ) {

    return $item

  }

}

The Get-Directory function uses Test-Path to determine if its parameter ($item) is a container object and a file system directory (that is, a System.IO.DirectoryInfo object).

If the Get-Directory function returned $null, the script writes an error to the error stream by using the Write-Error cmdlet and exits the Process script block with the return keyword.

After validating that the directory exists in the file system, the script calls the Get-DirectoryStats function, which is really the workhorse function in the script. The Get-DirectoryStats function is basically a fancy version of the commands run in Figure 1. Here it is:

function Get-DirectoryStats {

  param( $directory, $recurse, $format )

  Write-Progress -Activity “Get-DirStats.ps1” -Status “Reading ‘$($directory.FullName)’”

  $files = $directory | Get-ChildItem -Force -Recurse:$recurse | Where-Object { -not $_.PSIsContainer }

  if ( $files ) {

    Write-Progress -Activity “Get-DirStats.ps1” -Status “Calculating ‘$($directory.FullName)’”

    $output = $files | Measure-Object -Sum -Property Length | Select-Object `

      @{Name=”Path”; Expression={$directory.FullName}},

      @{Name=”Files”; Expression={$_.Count; $script:totalcount += $_.Count}},

      @{Name=”Size”; Expression={$_.Sum; $script:totalbytes += $_.Sum}}

  }

  else {

    $output = “” | Select-Object `

      @{Name=”Path”; Expression={$directory.FullName}},

      @{Name=”Files”; Expression={0}},

      @{Name=”Size”; Expression={0}}

  }

  if ( -not $format ) { $output } else { $output | Format-Output }

}

This function uses the Write-Progress cmdlet to inform the user running the script that something’s happening, and it uses a combination of the Get-ChildItem, Where-Object, Measure-Object, and Select-Object cmdlets to output a custom object. Note the use of the scoped variables ($script:totalcount and $script:totalbytes). These are used with the script’s Total parameter, and they are output in the script’s End script block.

Drop this script into a directory in your path, and you can quickly find the sizes for directories in your file system. Remember that it outputs objects, so you can add tasks such as sort and filter, for example:

Get-DirStats -Path C:\Temp | Sort-Object -Property Size

This command outputs the size of directories in C:\Temp, sorted by size.

The entire script can be downloaded from the Script Repository.

~Bill

Thank you, Bill, for writing an interesting and useful blog. Join me tomorrow for more Windows PowerShell cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

Author

The «Scripting Guys» is a historical title passed from scripter to scripter. The current revision has morphed into our good friend Doctor Scripto who has been with us since the very beginning.

Checking an item’s or a folder’s size is pretty easy on all Windows computers. Just right-click the directory/item, click Properties, and you have the size in front of you. Correct?

Not everyone is as lucky as you. If the size of an item is significantly larger, say greater than 100 GB, then it can take a while for the Properties window to finally populate the size of the item. There surely has to be a quicker way to check the folder size.

You may need the size of a folder so you can estimate the time it will take to move it or to free up space on your hard drive. For whatever reason, you can instantly get the size of a folder/directory using Windows PowerShell.

This article shows you different cmdlets and how to use their switches to get the size of a folder on your PC almost instantly using PowerShell.

We have a separate guide on how to get folder sizes using File Explorer and third-party apps.

Commands to Get Folder Size in PowerShell

There are 2 primary commands that you can use in PowerShell to get the size of a folder. These commands can be used together with switches and parameters to filter the results further.

  • Command: Get-ChildItem

    Alias: gci

    An alias is an alternative name you can use for the command so you won’t have to type in the entire command every time.

    Details: This command grabs the information from one or specified directories, including the sub-directories. However, it does not display the empty directories.

  • Command: Measure-Object

    Alias: measure

    Details: This command is used to calculate the different properties of a specified directory, including its size.

These are the two primary cmdlets that we will be using today to get the size of a folder using PowerShell.

Get Folder Size Using PowerShell

Below are a few commands that you can use to get the size of a folder on your Windows PC. Note that this section only lists the cmdlets that will get you the size of the specified folder and the items inside only, and the results will not include the size of the items inside the sub-directories.

If you want to get the size of the items inside the sub-directories as well, refer to the next section below.

Let us now continue with the example of checking the size of the “D:\iTechtics\ISOs” folder we have on our PC. Note that you must replace the [PathToFolder] with the complete path to the folder/directory for which you want to get the size.

Run the following command to get the size of a folder in bytes:

Get-ChildItem [PathToFolder] | Measure-Object -Property Length -sum
Get folder size using PowerShell in Bytes

Get folder size using PowerShell in Bytes

The “Sum” field will display the size of the folder in Bytes, as in the image above. The approximate size of the items inside the “ISOs” folder is 83 GBs.

Note: The size in Bytes needs to be divided by 1024 to get the size in KiloBytes, then another 1024 for MegaBytes, and then another 1024 for GigaBytes. However, you do not need to perform this calculation since you can get the answer directly in MBs or GBs (discussed below).

To get the size of a folder in MBs or GBs, use the respective command below:

  • For MBs:

    (gci [PathToFolder] | measure Length -s).sum / 1Mb
    Get folder size using PowerShell in MBs

    Get folder size using PowerShell in MBs
  • For GBs:

    (gci [PathToFolder] | measure Length -s).sum / 1Gb
    Get folder size using PowerShell in GBs

    Get folder size using PowerShell in GBs

As you can see in the images above, the size in MBs and GBs is ambiguous to understand at a glance due to the size being in many decimal places. You can round off the result of the command using the following cmdlet while replacing “X” with the number of decimal places you want to round off your answer to.

Note: Replace “GB” and “MB” as needed.

"{0:NX} GB" -f ((gci [PathToFolder] | measure Length -s).sum / 1Gb)
Get folder size rounded off to decimal using PowerShell

Get folder size rounded off to decimal using PowerShell

Additionally, you can also get the size of all the items inside a folder having the same file type/extension. This command syntax can be used for this purpose where the file size of all items with the “.ISO” extension will be displayed:

(gci [PathToFolder] *.iso | measure Length -s).sum / 1Gb
Get size of specific file type items using PowerShell

Get size of specific file type items using PowerShell

Get Folder And Sub-Folder Sizes Using PowerShell

Up until now, all commands that we have discussed will show you the combined size of the individual items in the specified directory. If the parent directory has sub-directories, then the size of the items would not be accumulated in the results.

To get the size of the items inside the sub-folders as well, you must use the “-Recurse” parameter. This is used in conjecture with “-ErrorAction SilentlyContinue” to bypass directory access errors like “Permission is denied” etc.

Here are two examples of using the “-Recurse” parameter to get the size of the parent as well as the sub-directories:

(gci [PathToFolder] –Recurse -ErrorAction SilentlyContinue| measure Length -s).sum / 1Gb
"{0:NX} GB" -f ((gci –force [PathToFolder] –Recurse -ErrorAction SilentlyContinue| measure Length -s).sum / 1Gb)
Get folder and sub folder sizes using Recurse parameter in PowerShell

Get folder and sub-folder sizes using -Recurse parameter in PowerShell

Note that this cmdlet will also include the sizes of any hidden items.

On top of finding out the size of the parent and the child folders, you can also apply filters. For example, you can find the size of the items created on a specific day, a specific month, or a specific year. These are defined by putting in the starting and the ending dates, which are respectively defined by the “-gt” (greater than) and “-lt” (less than) parameters.

Here is the syntax for getting the size of a folder with sub-folders created in April 2022:

Note: The format of the dates is MM/DD/YY.

(gci -force [PathToFolder] –Recurse -ErrorAction SilentlyContinue | ? {$_.CreationTime -gt ‘4/1/22’ -AND $_.CreationTime -lt ‘4/30/22’}| measure Length -s).sum / 1Gb
Get folder and sub folder sizes with time filter using PowerShell

Get folder and sub-folder sizes with time filter using PowerShell

You can also apply these filters using the commands given earlier to get the folder sizes of the parent folders only.

Now, to make things more complicated, let’s assume that you must get the size of each sub-directory inside a folder. That can also be accomplished using PowerShell. Of course, the results will be inclusive of the size of the items inside the sub-directories and presented in a neat, tabular format.

That said, for this to work, you must either allow scripts to run inside PowerShell or use PowerShell ISE to run the following script:

$targetfolder='D:\'
$dataColl = @()
gci -force $targetfolder -ErrorAction SilentlyContinue | ? { $_ -is [io.directoryinfo] } | % {
$len = 0
gci -recurse -force $_.fullname -ErrorAction SilentlyContinue | % { $len += $_.length }
$foldername = $_.fullname
$foldersize= '{0:N2}' -f ($len / 1Gb)
$dataObject = New-Object PSObject
Add-Member -inputObject $dataObject -memberType NoteProperty -name “foldername” -value $foldername
Add-Member -inputObject $dataObject -memberType NoteProperty -name “foldersizeGb” -value $foldersize
$dataColl += $dataObject
}
$dataColl | Out-GridView -Title “Size of all subdirectories in D drive”
Get all subdirectory folder sizes using PowerShell script

Get all subdirectory folder sizes using PowerShell script

Of course, you can change the directory to scan as well as the name of the output file in the script given above.

Takeaway

No matter how big a file or a folder is, using PowerShell, you can instantly determine its size and plan ahead.

The methods shared in this post allow you to get the size of a folder, a folder as well as its subdirectories, the size of a specific file type items inside a folder, or even filter it during a specific time. Take your pick and find out the size of your folder(s).

These methods are especially useful if you wish to determine the size of a database before migration, site backups, or if you just want to clear out some space on the hard drive.

PowerShell Get Folder Size: Find It Now

 When managing your computer’s storage or dealing with specific directories, it’s essential to know the size of a folder. PowerShell, a powerful automation and scripting language, can come to your rescue. In this article, we’ll explore how to use PowerShell to get the size of a folder, and we’ll provide you with useful scripts and tips to simplify the process.

PowerShell Basics

Before diving into folder size calculations, let’s cover some fundamental PowerShell concepts.

Get-ChildItem Cmdlet

Get-ChildItem is a versatile cmdlet in PowerShell that allows you to retrieve a list of items in a specified location. When used with the –Recurs parameter, it can traverse through subdirectories as well, making it perfect for our folder size calculations.

Measure-Object Cmdlet

Measure-Object is another handy cmdlet that, as the name suggests, measures various properties of objects. In our case, we’ll use it to calculate the size of folders by summing up the Length property of files within those folders.

Quick and Easy Folder Size Retrieval

The Quick and Dirty One-Liner

If you’re looking for a quick way to get the size of a folder in PowerShell, this one-liner is your go-to command:

“{0} MB” -f ((Get-ChildItem C:\users\ -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1MB)

This command fetches the folder size of the C:\users directory in megabytes.

The Not-So-One-Liner

For those who prefer a more comprehensive script, we’ve created a PowerShell module that provides folder sizes in megabytes and gigabytes. You can find the module on GitHub.

To install it from the PowerShell Gallery, use the following command:

Install-Module PSFolderSize

For detailed instructions on how to run it, check the help documentation:

Get-Help Get-FolderSize -Detailed

The latest version, 1.7.0, offers features such as sorting the output by FolderName or SizeBytes and exporting the results as CSV, JSON, or XML files.

The Script in Action

Let’s take a closer look at how this script works in various scenarios:

Basic Usage

.\Get-FolderSize.ps1

This command retrieves folder sizes for all folders in the default base path (C:\Users) and displays them in megabytes and gigabytes. Empty folders are omitted.

Specifying a Different Base Path

You can specify a different base path using the –BasePath parameter:

.\Get-FolderSize.ps1 -BasePath ‘C:\Program Files’

This command fetches folder sizes for the ‘C:\Program Files’ directory.

Filtering by Folder Name

To retrieve the size of a specific folder within the base path, use the -FolderName parameter:

.\Get-FolderSize.ps1 -BasePath ‘C:\Program Files’ -FolderName IIS

This command specifically fetches the folder size of ‘IIS’ within ‘C:\Program Files’.

Copying and Using the Code

Feel free to copy and paste the provided PowerShell script and use it according to your needs. It’s a valuable tool for obtaining folder sizes efficiently.

Advanced Features

  • Sorting by Size

You can sort the folder sizes by size, either in ascending or descending order. Here’s an example of sorting by size in descending order:

$getFolderSize = .\Get-FolderSize.ps1 | Sort-Object ‘Size(Bytes)’ -Descending$getFolderSize 

This command sorts the folder sizes from largest to smallest.

  • Omitting Specific Folders

The -OmitFolders parameter allows you to exclude specific folders from being included in the calculations. For example:

.\Get-FolderSize.ps1 -OmitFolders ‘C:\Temp’,’C:\Windows’

This command excludes the ‘C:\Temp’ and ‘C:\Windows’ folders from the folder size calculations.

Why Choose PowerShell for Folder Size Calculation?

When it comes to calculating folder sizes, PowerShell stands out as a versatile and efficient tool. Here are some compelling reasons to choose PowerShell:

  • Simplicity: PowerShell’s Get-FolderSize cmdlet provides a straightforward and user-friendly way to determine folder sizes;
  • Resource Efficiency: PowerShell is designed to be resource-efficient, making it an excellent choice for folder size calculations without causing system strain;
  • Customization: PowerShell offers extensive customization options, allowing you to tailor your folder size calculations to specific requirements;
  • Clear Output: With PowerShell, you can easily obtain folder sizes in both megabytes (MB) and gigabytes (GB), providing a clear and concise view of your data;
  • Robust Error Handling: PowerShell’s error handling capabilities ensure that your folder size calculations are reliable, even when dealing with complex directory structures;
  • Sorting and Filtering: PowerShell allows you to sort and filter results, making it easy to identify the largest or smallest folders within a directory;
  • Scalability: PowerShell is highly scalable, making it suitable for both small projects and enterprise-level folder size analysis;
  • Active Community: PowerShell benefits from an active and supportive community, offering assistance and solutions for various scenarios;
  • Documentation: PowerShell is well-documented, with a wealth of online resources and tutorials available to help you make the most of its features;
  • Cross-Platform Compatibility: PowerShell is cross-platform, ensuring that you can perform folder size calculations on different operating systems.

By choosing PowerShell for folder size calculations, you gain a powerful tool that simplifies the process while providing flexibility and accuracy. Whether you’re managing personal files or overseeing large-scale data storage, PowerShell offers a reliable solution.

Video Guide

To finally answer all your questions, we have prepared a special video for you. Enjoy watching it!

Comparison of Folder Size Calculation Methods

Method Ease of Use Resource Efficiency Customization Output Clarity Error Handling Sorting and Filtering Scalability Community Support
PowerShell (Get-FolderSize) High High Extensive Yes Robust Yes High Active Well-documented Cross-platform
Command Prompt (DIR) Moderate Moderate Limited No Basic No Limited Limited Limited No
Third-Party Tools Variable Variable Variable Variable Variable Variable Variable Variable Variable Variable

This table provides an overview of different folder size calculation methods, highlighting their key attributes. It can help readers understand the strengths and weaknesses of each approach when it comes to determining folder sizes.

Conclusion 

In conclusion, accurately determining the size of folders on your system is essential for effective storage management. Each method discussed in this article has its merits and is suitable for different scenarios.

PowerShell’s Get-FolderSize emerges as a robust and versatile solution, offering a high level of ease of use, resource efficiency, customization options, and robust error handling. It provides clear and well-documented results and enjoys strong community support, making it an excellent choice for many users. Moreover, its cross-platform compatibility adds to its appeal.

Command Prompt’s DIR command is a more basic option, offering moderate ease of use and resource efficiency. It may suffice for simple tasks but lacks the customization, error handling, and advanced features provided by PowerShell.

Third-party tools provide a wide range of options, each with its own set of characteristics. While they offer varying levels of ease of use, resource efficiency, and customization, their suitability depends on individual preferences and requirements. They may be valuable additions to your toolkit for specific tasks.

Ultimately, the choice of method depends on your specific needs, familiarity with the tools, and the complexity of the tasks at hand. PowerShell’s Get-FolderSize stands out as a comprehensive and powerful solution for most users, ensuring that you have precise information about your folder sizes, which is crucial for efficient system management.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как отключить autologon windows xp
  • Как вручную установить графический драйвер intel в windows 10
  • Windows xp bliss background
  • 80070422 net framework windows 10
  • Openfoam для windows 7