2
\$\begingroup\$

I'm trying to output aggregate information about a directory tree (file extension plus accumulative count and size per file type) with PowerShell.

This is as far as I've got.

gci -r -ea Si ` | group { if ($_.PSIsContainer) {""} else {$_.Extension} } ` | select Name, Count, @{n="Measure"; e={$_.Group | measure Length -Sum -Average} }` | sort Count -desc ` | ft Name, Count, @{n="SizeMB"; e={"{0:N1}" -f ($_.Measure.Sum / 1MB)}; a="right"} -Auto 

which gives me

Name Count SizeMB ---- ----- ------ .jar 2489 262,2 1592 1,2 .vim 1147 7,1 .xml 1087 9,6 .dll 803 657,3 .png 762 9,1 .js 380 1,9 .txt 360 14,1 .py 305 1,4 .gyp 266 0,3 .exe 262 198,3 .mui 178 47,1 .c 157 0,1 .md 137 0,3 .html 132 1,1 .tmpl 113 0,1 [...] 

Not too bad for my first stab at PowerShell, but it feels unwieldy and I'm wondering if this could be made more elegant.

\$\endgroup\$

    1 Answer 1

    2
    \$\begingroup\$

    You are running your select twice and saving an unused Average from your Select-Object

    gci -r -ea Si ` | group { if ($_.PSIsContainer) {""} else {$_.Extension} } ` | sort Count -desc ` | ft Name, Count, @{n="SizeMB"; e={"{0:N1}" -f (($_.Group | measure Length -Sum).Sum / 1MB)};a="right"} -Auto 

    You have to move the Group Measurement to the FT line from the Select.

    If you want this a little more readable, you can pull the formatting HashTable out of the pipeline:

    $sizeMB = @{n="SizeMB"; e={"{0:N1}" -f (($_.Group | measure Length -Sum).Sum / 1MB)}; a="right"} gci -r -ea Si ` | group { if ($_.PSIsContainer) {""} else {$_.Extension} } ` | sort Count -desc ` | ft Name, Count, $sizeMB -Auto 
    \$\endgroup\$

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.