Saturday, June 20, 2020

power(shell), corruption & lies: Directory Info Aggregation

To get a recursive summary of files, folders and sizes from a root directory:

$len=0; Get-ChildItem -Recurse | 
    %{ $_.GetType().Name; $len+=$_.Length } | 
    Group-Object -NoElement | ft -auto; "Total size= $($len / 1Gb) GB"

Output looks like this
Count Name
----- ----
18386 DirectoryInfo
57784 FileInfo
Total size= 25.7907013082877 GB
 
How it works:

  1. $len=0 sets the variable len to 0. No duh here.
  2. Get-ChildItem -Recurse recurses through a directory tree from the current directory. You can use the -Path option for a different root directory.
  3. %{} is the alias of ForEach-Object and is a shorthand way of looping over results that are piped from the previous command
  4. $_.GetType().Name is emitting the type of the directory entry (DirectoryInfo or FileInfo)
  5. $len+=$_.Length is summing up directory entry sizes
  6. Group-Object -NoElement is counting directory entry types from step 4 and printing them out.
  7. ft -auto automatically formats the output so that large numbers are not truncated to ellipsis (...).
  8. "Total size= $($len / 1Gb) GB" prints out the total accumulated size from the $len variable in Gigabytes.

No comments:

Post a Comment