Wednesday, July 2, 2014

Delete work items from TFS or VSO

Have you ever created a bunch of work items that you decided later that you had to delete. Well I have… especially as a user of the TFS Integration Platform. And when things go wrong there they can really go wrong.

Now while you can put stuff into the “removed” state it is still hanging around cluttering up the place. The only way out of the box to remove items is to give the ID for each work item that you want to delete and execute the command line for each one:

witadmin destroywi /collection:CollectionURL /id:id [/noprompt]

Well that’s just great unless you have a couple of thousand things to delete. 
So I've written a little bit of code to do it for me; in this example I created a small console program but you can use the same code in any kind of project.

using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;


TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri("http://your_tfs_url:8080/tfs/CollectionName"));
WorkItemStore store = tpc.GetService();

string query = @"SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = 'projectName'  AND  [System.AreaPath] UNDER 'projectName\_TOBEDELETED' ORDER BY [System.Id]";

WorkItemCollection wis = store.Query(query);
var wisIds = wis.Select( wi => wi.Id);

Console.WriteLine(string.Format("DESTROY {0} work items (they really can't be resurrected): y/n?", wis.Count));
ConsoleKeyInfo cki = Console.ReadKey();

if (cki.Key.ToString().ToLower() == "y")
  var items = store.DestroyWorkItems(wisIds.ToArray());
  foreach (var item in items)
 catch (Exception ex)



The first thing that you may notice is that I search for items in a specific area path. I use _TOBEDELETED as it is obvious what is going to happen to things that end up there. Although I did work with a user who complained that all his files had gone missing. When asked where he kept them he pointed at the recycle bin on his desktop!

Anyhow, just in case you made a mistake it will let you know how many work items that you are deleting. It’s a simple check but I have had it say "100000" work items... AS you can imagine I very carefully terminated the program (never trust the 'no' option).

No comments: