Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer

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
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.