Discussion
When disk space starts running low, you’ll naturally want to find out where to focus your cleanup efforts. Sometimes, you may tackle this by looking for large directories (including the directories in them), but other times, you may solve this by looking for directories that are large simply from the files they contain.
Example 172 collects both types of data. It also demonstrates an effective use of calculated properties. Like the AddMember cmdlet, calculated properties let you add properties to output objects by specifying the expression that generates their data.
Example 172. GetDiskUsage.ps1
############################################################################## ## ## GetDiskUsage.ps1 ## ## Retrieve information about disk usage in the current directory and all ## subdirectories. If you specify the IncludeSubdirectories flag, this ## script accounts for the size of subdirectories in the size of a directory. ## ## ie: ## ## PS >GetDiskUsage ## PS >GetDiskUsage IncludeSubdirectories ## ##############################################################################
param( [switch] $includeSubdirectories )
## If they specify the IncludeSubdirectories flag, then we want to account ## for all subdirectories in the size of each directory if($includeSubdirectories) {
GetChildItem | WhereObject { $_.PsIsContainer } |
SelectObject Name, @{ Name="Size"; Expression={ ($_ | GetChildItem Recurse |
MeasureObject Sum Length).Sum + 0 } } } ## Otherwise, we just find all directories below the current directory, ## and determine their size else {
GetChildItem Recurse | WhereObject { $_.PsIsContainer } |
SelectObject FullName, @{ Name="Size"; Expression={ ($_ | GetChildItem |
MeasureObject Sum Length).Sum + 0 } } }