Skip to content

Get folder sizes of a specified directory or directories (a Windows PowerShell script).

License

Notifications You must be signed in to change notification settings

auberginehill/get-directory-size

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

45 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Get-DirectorySize.ps1

OS: Windows
Type: A Windows PowerShell script
Language: Windows PowerShell
Description: Get-DirectorySize returns the size of a directory or directories (paths) specificed by a parameter called -Path and reports the sizes of the first level of folders (i.e. the listing is similar to the common "dir" command, but the size of the folders is shown in the results and the listing of files is omitted).

To query recursively (i.e. including all sub-directories of the sub-directories and their sub-directories as well and also all other successive sub-directories) a parameter -Recurse may be added to the query command.

To effectively use Get-DirectorySize, a path, paths or path names to a directory should be specified (with the -Path parameter), as by default, only $env:temp gets searched. The paths should be valid file system paths to a directory (a full path name of a directory (i.e. folder path such as C:\Windows)). In case the path name includes space characters, quotation marks around the path name are mandatory. The -Path parameter accepts a collection of path names (separated by comma) and also takes an array of strings for paths to query.

The directories are queried extensively, a wide array of properties, such as Directory, Owner, Size, Relative Size (Size (%)), raw_size, File Count, Subfolder Count, Average File Size, Average File Size (B), Written, Written Ago (h), Age (Days), Read, Read ago (h), Created on, Last Updated, BaseName, PSChildName, Last AccessTime, Last WriteTime, Creation Time, Extension, Is ReadOnly, Exists, PS Is Container, Attributes, VersionInfo, Folder Name, Name, Parent, Root, PSParentPath, PSPath, PSProvider, Last WriteTime (UTC), Creation Time (UTC), Last AccessTime (UTC), PSDrive, Volume Available Free Space (B), Volume Type, Volume Free, Volume Free (%), Volume Is Ready, Volume Label, Volume Name, Volume Root Directory, Volume Total Size, Volume Total Free Space (B), Volume Total Size (B), Volume Used, Volume Used (%) and Volume is leveraged from the directories totaling over 50 headers / columns. The full report is written to a CSV-file, about 1/2 of the data is displayed in a sortable pop-up window (Out-GridView) and a Directory Size Report (as a HTML file) with the essential information is invoked in the default browser.

The -ReportPath parameter defines where the files are saved. The default save location of the HTML Directory Size Report (directory_size.html) and the adjacent CSV-file (directory_size.csv) is $env:temp, which points to the current temporary file location, which is set in the system (– for more information, please see the Notes section).

While the parameters -Path, -Recurse and -ReportPath (along with the -Audio parameter(, which emits an audible beep after the query is finished)) modify holistically the behavior of Get-DirectorySize, the other parameters -Sort and -Descending toggle how and in which way the data is displayed in the HTML Directory Size Report. The usage and behavior of each parameter is discussed in further detail below. This script is based on Martin Pugh's PowerShell script "Get-FolderSizes".
Homepage: https://github.com/auberginehill/get-directory-size
Short URL: http://tinyurl.com/jjl9wng
Version: 1.2
Sources:
Emojis: Emoji Table
Martin Pugh: Get-FolderSizes
Joel Reed: Get-DirectorySize
Brian: Making PowerShell Emails Pretty
clayman2: DiskSpace (or one of the archive.org versions)
Tobias Weltner: PowerTips Monthly Volume 2: Arrays and Hash Tables (or one of the archive.org versions)
Microsoft TechNet: Invoke-Command
Microsoft TechNet: Sort-Object
Downloads: For instance Get-DirectorySize.ps1. Or everything as a .zip-file.

Screenshot

screenshot

Parameters

📐
  • Parameter -Path

    as an alias of -Paths. The -Path parameter determines the starting point of the directory size analyzation. The -Path parameter also accepts a collection of path names (separated by a comma). It's not always mandatory to write -Path in the query command to invoke the -Path parameter, as is shown in the Examples below, since Get-DirectorySize is trying to decipher the inputted queries as good as it is machinely possible within a 60 KB size limit.

    The paths should be valid file system paths to a directory (a full path name of a directory (i.e. folder path such as C:\Windows)). In case the path name includes space characters, please add quotation marks around the path name. If a collection of path names is defined for the -Path parameter, please separate the individual path names with a comma. The -Path parameter also takes an array of strings for paths to query and objects could be piped to this parameter, too. If no path is defined in the query $env:temp gets searched.

  • Parameter -ReportPath

    Specifies where the HTML Directory Size Report and the adjacent CSV-file is to be saved. The default save location is $env:temp, which points to the current temporary file location, which is set in the system. The default -ReportPath save location is defined at line 16 with the $ReportPath variable. For usage, please see the Examples below and for more information about $env:temp, please see the Notes section below.

  • Parameter -Sort

    Specifies which column is the primary sort column in the HTML Directory Size Report. Only one column may be selected in one query as the primary column. If -Sort parameter is not defined, Get-DirectorySize will try to sort by Size.

    Even when the -Sort parameter is used, Get-DirectorySize acts partially indepently in the background and is actively trying to sort values automatically, so that numerical values would be sorted as descending as default while text based columns would be sorted as ascending as default. By any means with any command or parameter combination will Get-DirectorySize probably not agree to sorting size in the HTML Directory Size Report as ascending, so effectively the -Descending parameter is almost exclusively left as a toggle for the text based columns.

    In the HTML Directory Size Report all the headers are sortable (with the query commands) and some headers have aliases, too. Valid -Sort values are listed below along with the default order (descending or ascending). Please also see the Examples section for further usage examples.

      Valid -Sort values:

      Value Sort Behavior Default Order
      Descending Ascending
      Directory Sort by Directory (param) Ascending
      Owner Sort by Owner (param) Ascending
      Size Sort by raw_size Descending -
      "Size (%)" Sort by Size (%) Descending -
      raw_size Sort by raw_size Descending -
      Files Sort by Files Descending -
      Subfolders Sort by Subfolders Descending -
      "Average File Size" Sort by Average File Size (B) Descending -
      "Average File Size (B)" Sort by Average File Size (B) Descending -
      Average Sort by Average File Size (B) Descending -
      "Written Ago (h)" Sort by Written Ago (h) (param) Ascending
      Written Sort by Written Ago (h) (param) Ascending
      "Age (Days)" Sort by Age (Days) (param) Ascending
      Age Sort by Age (Days) (param) Ascending
      "Read ago (h)" Sort by Read ago (h) (param) Ascending
      Read Sort by Read ago (h) (param) Ascending
      "Created on" Sort by Created on (param) Ascending
      Created Sort by Created on (param) Ascending
      "Last Updated" Sort by Last Updated (param) Ascending
      Updated Sort by Last Updated (param) Ascending
      Changed Sort by Last Updated (param) Ascending
      Last Sort by Last Updated (param) Ascending
      "Folder Name" Sort by Folder Name (param) Ascending

      In the table above, (param) depicts the usage of the -Descending parameter.

  • Parameter -Descending

    A switch to control how directories get sorted in the HTML Directory Size Report. Please see the -Sort parameter above for further details. By default Get-DirectorySize tries to sort number based values in an descending order and text based values in an ascending order. By adding the -Descending parameter to the query the prevalent ascending sort order may be reversed in the cases, which are listed in the table above and marked with (param).

  • Parameter -Recurse

    If the -Recurse parameter is added to the query command, also each and every sub-folder in any level, no matter how deep in the directory structure or behind how many sub-folders, is included individually to the report. While the -Recurse parameter can be used for reporting the size of all sub-folders on every sub-level, it may have an impact on how long the script actually runs.

    Please note, that even when the -Recurse parameter is not used, and despite its toll to the performance of the script (speed), Get-DirectorySize will try to query some data, such as the overall size of the folder, recursively. This is intended action and is one of the key elements and main characteristics of Get-DirectorySize. The total size of a folder cannot be known, if all of the content is not known. The file count and subfolder count will, however, follow the path of the -Recurse parameter. Furthermore, since the Average File Size depends on the number of files found, the reported average file size of a folder may differ drastically depending on whether the -Recurse parameter was used or not.

  •                   <li>
                        <h5>Parameter <code>-Audio</code></h5>
                        <p>If this parameter is used in the query command, an audible beep will occur after the directory size enumeration is finished.</p>
                    </li>
                </p>
            </ul>
        </td>
    </tr>
    

Outputs

➡️
  • Generates an HTML Directory Size Report and an adjacent CSV-file in a specified Report Path ($ReportPath = "$env:temp" at line 16), which is user-settable with the -ReportPath parameter. Skipped path names, if any, are reported in console. Also displays performance related information about the query process in console after the query has finished. In addition to that...

  • One pop-up window "$results_selection" (Out-GridView) with sortable headers (with a click):
    1. Name Description
      $results_selection Displays 1/2 of the full data set

  • And also the aforementioned HTML-file "Directory Size Report" and CSV-file at $ReportPath. The HTML-file "Directory Size Report" is opened automatically in the default browser after the query is finished.
    1. Path Type Name
      $env:temp\directory_size.html HTML-file directory_size.html
      $env:temp\directory_size.csv CSV-file directory_size.csv

Notes

⚠️
  • Please note that all the parameters can be used in one query command and that each of the parameters can be "tab completed" before typing them fully (by pressing the [tab] key).

  • Please note that the default search location is defined at line 15 for the -Path parameter (as an alias of -Paths) with the $Paths variable.
  • Please also note that the two files are created in a directory, which is end-user settable in each query command with the -ReportPath parameter. The default save location is defined with the $ReportPath variable (at line 16). The $env:temp variable points to the current temp folder. The default value of the $env:temp variable is C:\Users\<username>\AppData\Local\Temp (i.e. each user account has their own separate temp folder at path %USERPROFILE%\AppData\Local\Temp). To see the current temp path, for instance a command

    [System.IO.Path]::GetTempPath()

    may be used at the PowerShell prompt window [PS>]. To change the temp folder for instance to C:\Temp, please, for example, follow the instructions at Temporary Files Folder - Change Location in Windows, which in essence are something along the lines:
    1. Right click on Computer and click on Properties (or select Start → Control Panel → System). In the resulting window with the basic information about the computer...
    2. Click on Advanced system settings on the left panel and select Advanced tab on the resulting pop-up window.
    3. Click on the button near the bottom labeled Environment Variables.
    4. In the topmost section labeled User variables both TMP and TEMP may be seen. Each different login account is assigned its own temporary locations. These values can be changed by double clicking a value or by highlighting a value and selecting Edit. The specified path will be used by Windows and many other programs for temporary files. It's advisable to set the same value (a directory path) for both TMP and TEMP.
    5. Any running programs need to be restarted for the new values to take effect. In fact, probably also Windows itself needs to be restarted for it to begin using the new values for its own temporary files.

Examples

📖 To open this code in Windows PowerShell, for instance:

  1. ./Get-DirectorySize
    Run the script. Please notice to insert ./ or .\ before the script name. Uses the default location ($env:temp) for 'listing the contents of' and for storing the generated two files. Lists the folders, which are found on the first level (i.e. search is done nonrecursively, similarly to a common command "dir", for example). The output in the CSV file includes nearly 40 columns of data with each processed folder name as a row, the Out-GridView has about 1/2 of the data and, in essence, the generated HTML Directory Size Report is a summary table with the most relevant information. The HTML Directory Size Report is sorted by Size and ordered as descending as default (the default order for text based columns is ascending).
  2. help ./Get-DirectorySize -Full
    Display the help file.
  3. ./Get-DirectorySize -Path "C:\Windows" -ReportPath "C:\Scripts"
    Run the script and report on all folders in C:\Windows. Save the HTML Directory Size Report and the adjacent CSV-file to C:\Scripts. The output is sorted, as per default, on the raw_size property in an descending order, displaying the largest directories on top and the smallest directories at the bottom.
  4. ./Get-DirectorySize "C:\dc01","D:\dc04","E:\chiore"
    Run the script and report on all folders, which are found in C:\dc01, D:\dc04 and E:\chiore. Please note that the -Path is not mandatory in this example, but it could be included, too, and the quotation marks can be left out since the path names don't contain any space characters (./Get-DirectorySize -Path C:\dc01, D:\dc04, E:\chiore).
  5. ./Get-DirectorySize -Path E:\chiore -Sort Directory -Descending
    Run the script and report on all the folders in E:\chiore. Sort the data based on the "Directory" column and arrange the rows in the HTML Directory Size Report as descending so that last alphabets come to the top and first alphabets will be at the bottom. To sort the same query in an ascending order the -Descending parameter may be left out from the query command (./Get-DirectorySize -Path E:\chiore -Sort Directory). The sort column name is case-insensitive (as is most of the PowerShell), and since the path name doesn't contain any space characters, it doesn't need to be enveloped with quotation marks. Actually the -Path parameter may be left out from the query command, too, since, for example,

    ./get-directorysize e:\cHIORe -sort directory -descending

    is the exact same query command in nature.
  6. ./Get-DirectorySize -Path C:\Users\Dropbox -Recurse -Audio
    Will output a size calculation of C:\Users\Dropbox and include all enclosed sub-directories of the sub-directories of the sub-directories and their sub-directories as well (the search is done recursively). The output is sorted, as per default, on the raw_size property in an descending order, displaying the largest directories on top and the smallest directories at the bottom. After the the script has finished its work, an audible "bell" sound is evoked. Due to the partial automation in Get-DirectorySize, this is the same command as

    ./Get-DirectorySize -Path C:\Users\Dropbox -Sort size -Descending -Recurse -Audio

    in essence.
  7. ./Get-DirectorySize -Path C:\Windows -ReportPath C:\Scripts -Sort owner -Descending -Recurse
    Run the script and list recursively all the folders in C:\Windows, so that all sub-folders will get enumerated individually, too. Sort the data in the HTML Directory Size Report by the column name Owner in a descending order, and save the HTML Directory Size Report to C:\Scripts. Please note, that -Path can be omitted in this example, because

    ./Get-DirectorySize C:\Windows -ReportPath C:\Scripts -Sort owner -Descending -Recurse

    will result in the exact same outcome.
  8. Set-ExecutionPolicy remotesigned
    This command is altering the Windows PowerShell rights to enable script execution. Windows PowerShell has to be run with elevated rights (run as an administrator) to actually be able to change the script execution properties. The default value is "Set-ExecutionPolicy restricted".

    Parameters:

      Restricted Does not load configuration files or run scripts. Restricted is the default execution policy.
      AllSigned Requires that all scripts and configuration files be signed by a trusted publisher, including scripts that you write on the local computer.
      RemoteSigned Requires that all scripts and configuration files downloaded from the Internet be signed by a trusted publisher.
      Unrestricted Loads all configuration files and runs all scripts. If you run an unsigned script that was downloaded from the Internet, you are prompted for permission before it runs.
      Bypass Nothing is blocked and there are no warnings or prompts.
      Undefined Removes the currently assigned execution policy from the current scope. This parameter will not remove an execution policy that is set in a Group Policy scope.

    For more information, please type "help Set-ExecutionPolicy -Full" or visit Set-ExecutionPolicy.

  9. New-Item -ItemType File -Path C:\Temp\Get-DirectorySize.ps1
    Creates an empty ps1-file to the C:\Temp directory. The New-Item cmdlet has an inherent -NoClobber mode built into it, so that the procedure will halt, if overwriting (replacing the contents) of an existing file is about to happen. Overwriting a file with the New-Item cmdlet requires using the Force.
    For more information, please type "help New-Item -Full".

Contributing

Find a bug? Have a feature request? Here is how you can contribute to this project:

contributing Bugs: Submit bugs and help us verify fixes.
Feature Requests: Feature request can be submitted by creating an Issue.
Edit Source Files: Submit pull requests for bug fixes and features and discuss existing proposals.

www

www Script Homepage
Martin Pugh: Get-FolderSizes
Joel Reed: Get-DirectorySize
Brian: Making PowerShell Emails Pretty
clayman2: DiskSpace (or one of the archive.org versions)
Tobias Weltner: PowerTips Monthly Volume 2: Arrays and Hash Tables (or one of the archive.org versions)
Invoke-Command
Sort-Object
Windows PowerShell: Build a Better Function
ValidateSet Attribute Declaration
about_Functions_Advanced_Parameters
PowerShell: Advanced Function Parameter Attributes
Working with Hash Tables
10 PowerShell commands every Windows admin should know
ASCII Art: http://www.figlet.org/ and ASCII Art Text Generator

Related scripts

www Firefox Customization Files
Get-AsciiTable
Get-BatteryInfo
Get-ComputerInfo
Get-InstalledPrograms
Get-InstalledWindowsUpdates
Get-RAMInfo
Get-TimeDifference
Get-TimeZoneTable
Get-UnusedDriveLetters
Emoji Table
Java-Update
Rock-Paper-Scissors
Toss-a-Coin
Update-AdobeFlashPlayer