Removing folders smaller than n size

Caporegime
Joined
25 Jul 2003
Posts
40,281
Location
FR+UK
How might one achieve something similar to:

Code:
du | awk '$1 <= 1000000 { print "rm -rf \"" substr($0, length($1)+2) "\""}' | sh
(this searches for folders smaller than 1MB in size and removes them)

on a Windows server? I'm having a hunt for some powershell but my knowledge is pretty limited..
 
Ok for anyone thats interested, solved with some vb:

Code:
Dim objFD
Set objFD = CreateObject("Scripting.FileSystemObject")
Set objSelectedFolder = objFD.GetFolder("D:\scripttest\")
Set colSubfolders = objSelectedFolder.SubFolders
For Each objSubfolder In colSubfolders
If objSubfolder.Size < 10000000 Then
objSubfolder.Delete True
End If
Next

This will delete any folder less than 10Mb.
 
Just in case, here's a powershell way. Could probably be done in 1 line but those are just to difficult for my small mind to read so I like to spread them out a bit!

Code:
$TargetFolder = "C:\Scripts\FolderDelete\Example"
$FolderList = Get-ChildItem -Path $TargetFolder | Where {$_.PSIsContainer}
ForEach ($Folder In $FolderList)
{
    $Size = (Get-ChildItem $Folder.FullName -Recurse | Measure-Object -Property length -Sum | Select Sum).Sum / 1MB
    If ($Size -Gt 10)
    {
        Remove-Item -Path $Folder.FullName -Recurse -WhatIf
    }
}

First line sets the target variable
Next gets a list of folders at the target location. This won't recursively get a list of subfolders, just the root of the target.

For each folder have to count the size of it. Works by creating a collection of all the items in that folder and subfolders, then counts and keeps a sum of the length field. This returns some other fields we're not interested in so pipe it through and just select the Sum field.
Now have an object with one field, sum so can select it specifically by .Sum
Then can divide the total in bytes by 1mb to get the size in mb.

If it's greater than 10 delete it. Stuck a -whatif on the end so you can check it's not about to delete your whole network.
 
Back
Top Bottom