This is a cross-post from my blog, Demonic Talking Skull. This is something I put together for a client who wanted to know how much disk space their users' home directories were taking up on the file server before the admins went through and applied space quotas. The file server was running Windows Server 2008 R2.
#Query Folders
$dirpath = Read-Host "Enter path"
$subfolders = Get-ChildItem $dirpath | Where-Object {$_.PsIsContainer}
#Calculate sizes
foreach ($subfolder in $subfolders) {
$folder = $dirpath + "\" + $subfolder.Name
$colItems = (Get-ChildItem $folder -Recurse | Measure-Object -property length -sum)
$colItemsSum = ("{0:N2}" -f ($colItems.sum / 1MB) + " MB")
Write-Output $folder $colItemsSum | Out-File export.txt -Append
}
The script asks for a root folder (eg: D:\Users or \\servername\userhome - it works locally or remotely) and from there it finds all the subfolders one level down, calculates the size of each of the subfolders, and outputs the subfolder name and calculated size to export.txt.
If you're only interested in subfolders which actually have something in them (i.e. not interested in empty subfolders), then this code does the same thing, but checks each subfolder first and ignores it if there's nothing in it:
#Query Folders
$dirpath = Read-Host "Enter path"
$subfolders = Get-ChildItem $dirpath | Where-Object {$_.PsIsContainer}
#Calculate sizes
foreach ($subfolder in $subfolders) {
$folder = $dirpath + "\" + $subfolder.Name
if ($folder -ne $null){
$colItems = (Get-ChildItem $folder -Recurse | Measure-Object -property length -sum)
$colItemsSum = ("{0:N2}" -f ($colItems.sum / 1MB) + " MB")
Write-Output $folder $colItemsSum | Out-File export.txt -Append}
else {}
}
The data export is a little clunky, so if anyone could suggest a better methodology (such as export to CSV with columns) I'd be really interested. I think there's a limitation in the fact that I've used "foreach" rather than "Foreach-Object" as the output from the former can't be pipelined (or something like that) whereas the latter has more flexibility.
Edited by Elly Hart, 3.23am, August 6, 2010.
Enjoyed this post?
Help us spread the word by sharing with friends and colleagues!
Posted in: [IT Pros], [Windows Server], [Windows Client]
Popular tags: Powershell, windows server, Administrators