This is a small tool I wrote to list or delete all documents from a collection of Document libraries in SharePoint. 

It will search from the specified root url, and down, for all document Libraries with the specified name.

Note: It will look for document libraries with the same name.

One interesting thing I found when working on the code, was that if you iterate over the item collection via a for each (which will fail directly) or a for-next loop, you will not delete all the items.

I believe this is related to the changes you make to the collection by removing members, while you are iterating over it.

So I use a second iteration for the deletes now.

The command takes 3 parameters:

  1. Operation: Tell the tool if you want it to just list the files or to delete  the files.
  2. Url: This is the start url for the search for documents. Only sites that are at this level or below will be searched.
  3. DocLibraryName: This is the name of the document library to look for in each site. In our case it is always “Background Information Library

Get the source here, or download the binary here.

class

Program
{
static void Main(string[] args)
{

if (args.Length != 3)
{

Console.WriteLine("Usage: ShowAllDocuments [list|delete] <url> <DocLibraryName> ");

return;
}

string operation = args[0];
string url = args[1];
string name = args[2];

if (operation == "list" || operation == "delete")
{
SPSite site = new SPSite(url);
SPWeb web = site.OpenWeb();
FindDocumentLibraries(web, name, operation);
} else {
Console.Error.WriteLine("Unknown operation: " + operation);
}
}

public static void FindDocumentLibraries(SPWeb web, string name,string operation)
{
foreach (SPList list in web.Lists)
{
if (list.BaseType == SPBaseType.DocumentLibrary)
{
SPDocumentLibrary lib = list
as SPDocumentLibrary;
if (lib.Title == name)
{
List<string> filesToDelete = new List<string>();
foreach (SPListItem item in lib.Items)
{
SPFile file =
null;
try
{
file = item.File;
if (file != null)
{
filesToDelete.Add(file.Url);
Console.WriteLine(String.Format("In DocLib: {0} ({2}) File - {1} ({3})", web.Title, item.Name, web.Url, file.Length));
}
}
catch(Exception ex)
{
Console.Error.WriteLine("Something bad happened: " + ex.Message);
}

}

if (operation == "delete")
{
SPFolder folder = lib.ParentWeb.GetFolder(name);
foreach (string url in filesToDelete)
{
folder.Files.Delete(url);
Console.WriteLine("Deleted:" + url);
}
folder.Update();
lib.Update();

}
}
}
}

FindDocumentLibraries(web.Webs, name, operation);
}

 

public static void FindDocumentLibraries(SPWebCollection webs, string name,string operation)
{
if (webs != null && webs.Count > 0)
{
foreach (SPWeb web in webs)
{
FindDocumentLibraries(web, name, operation);
}
}
}
}