Mass Delete Empty Folders With PowerShell

If you don’t feel like manually deleting empty folders, use this PowerShell script to query and delete all empty folders and subfolders. Make sure you change the $WebURL to your SharePoint site or subsite, and the $listName to your library.


Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

function EmptyFolders()
{
$WebURL = "http://sp2013/sites/company"
$webDestination = Get-SPWeb -identity $WebURL
$listName = "Documents"

$query = New-Object Microsoft.SharePoint.SPQuery;
$query.ViewAttributes = "Scope='RecursiveAll'";
$query.RowLimit = 5000
$caml = "<Where>
<Eq>
<FieldRef Name='ContentType' />
<Value Type='Text'>Folder</Value>
</Eq>
</Where>"

$query.Query = $caml

$list = $webDestination.Lists[$listName]
$folder = $list.GetItems($query)
do
{
$query.ListItemCollectionPosition = $folder.ListItemCollectionPosition
for ($index = $folder.Count - 1; $index -gt -1; $index--)
{
if ($folder[$index]["FolderChildCount"].Replace(';#', '') -eq 0 -and $folder[$index]["ItemChildCount"].Replace(';#', '') -eq 0)
{
Write-Host("$($folder[$index]["FolderChildCount"].Replace(';#', '')), $($folder[$index]["ItemChildCount"].Replace(';#', '')), $($folder[$index]["ContentType"]), $($folder[$index].URL)")
$folder[$index].Delete();
$list.Update()
}
}
}
While($query.ListItemCollectionPosition -ne $null)
#$list.Update();
$webDestination.Dispose()
$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup("Operation Completed",0,"Done",0x1)
}
EmptyFolders

Advertisement

6 thoughts on “Mass Delete Empty Folders With PowerShell

  1. Appreciating the persistence you put into your site and detailed information you present. It’s great to come across a blog every once in a while that isn’t the same unwanted rehashed information. Excellent read! I’ve saved your site and I’m including your RSS feeds to my Google account.

  2. Good post. I learn something totally new and challenging on websites
    I stumbleupon on a daily basis. It’s always interesting to read through articles from other authors and use a little something from other
    web sites.

  3. Thank you, I have just been looking for info approximately this topic for a while and
    yours is the greatest I’ve discovered so far.
    But, what about the bottom line? Are you sure about the source?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s