Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

powershell - Determine recursively both COUNT and SUM of all extensions in a folder

I would like to be able to select a remote folder and scan it recursively for all file extensions. For each extension discovered, I would need a total count and well as the sum for individual file types.

I've found a script here that works for a single file extension using the -include switch, but rather than running the script scores of times, it would be nice to simply run once and collect all extensions.

$hostname=hostname
$directory = "D:foo"

$FolderItems = Get-ChildItem $directory -recurse -Include *.txt
$Measurement = $FolderItems | Measure-Object -property length -sum
$colitems = $FolderItems | measure-Object -property length -sum
"$hostname;{0:N2}" -f ($colitems.sum / 1MB) + "MB;" + $Measurement.count + " files;"

I think I need to use Get-ChildItem $directory | Group-Object -Property Extension to somehow list the extensions, if that's helpful.

The ideal output would be something like this:
Extension, Size (MB), Count
jpg,1.72,203
txt,0.23,105
xlsx,156.12,456

I'm using Powershell v4.0 on a Windows 7 machine to remotely connect to the server, I could run the script locally, but it only has V3.0 for the Win 2008 R2 machine.

Does anyone have any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is one approach:

#Get all items
Get-ChildItem -Path $directory -Recurse |
#Get only files
Where-Object { !$_.PSIsContainer } |
#Group by extension
Group-Object Extension |
#Get data
Select-Object @{n="Extension";e={$_.Name -replace '^.'}}, @{n="Size (MB)";e={[math]::Round((($_.Group | Measure-Object Length -Sum).Sum / 1MB), 2)}}, Count

Extension Size (MB) Count
--------- --------- -----
mkv          164,03     1
xlsx           0,03     3
dll            0,32     5
lnk               0     1
url               0     1
txt               0     1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...