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.

James Khoury
3,1651 gold badge25 silver badges51 bronze badges
asked Feb 23, 2013 at 22:32
\$\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
answered May 1, 2013 at 13:45
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.