Table of Contents



Introduction:

Few days back a contributor requested me to write a tool that will cleanup completed workflow instances from a list. Hence I have developed this script, it takes site url and list name as input and then it spans through all items in the list and clears up all completed workflow instances.

This works for sharepoint 2007 as well as sharepoint 2010. This can be executed from any WFE in the farm. The code is as below:

C# Code Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
 
 
namespace CompletedWorkflowCleanUp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter the site url");
            String siteUrl = Console.ReadLine();
            Console.WriteLine("Please enter the list title");
            String listName = Console.ReadLine();
            using (SPSite site = new SPSite(siteUrl))
            {
                SPWorkflowManager workflowManager = site.WorkflowManager;
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists[listName];
                    SPListItemCollection listItems = list.Items;
                    foreach (SPListItem listItem in listItems)
                    {
                        SPWorkflowCollection wCollection = listItem.Workflows;
                  
                        for (int i = 0; i < wCollection.Count; i++)
                        {
                            if (wCollection[i].IsCompleted)
                            {
                                workflowManager.RemoveWorkflowFromListItem(wCollection[i]);
                                listItem.Update();
                            }
 
 
                        }
                       
                    }
                    Console.WriteLine("Completed workflow instances are deleted for the list" +list);
                    Console.ReadLine();
                }
            }
        }
    }
}