Cancel all workflows in site collection efficiently
Here you will find a script to cancel all list workflows (not site workflows) running in a given site collection in the most efficient manner possible (that I can think of) while still only using the SharePoint API. A better approach still would be to query the SharePoint workflows SQL table to identify the running workflows so as to avoid iterating all site collection webs and lists. Unfortunately there is no ‘GetAllRunningWorkflows(SPSite)’ method available via the API. I imagine that this approach should be satisfactory in the majority of cases though.
There are a number of posts on the web with code somewhat similar to this, at least with code that aims to achieve the same outcome. Of all the posts which I found they all performed this function in a very inefficiency manner, iterating the SPListItemCollection for every list in the site collection. This may be fine in many circumstances but I wanted something that would run faster with less strain on the server.
I have achieved this by checking for workflow associations on a list before iterating the items as well querying the list items and where a workflow column exists checking to see if the list item needs to be returned at all. When returning the list items, I am querying with ViewFieldsOnly so that less data is returned.
This script also accepts an optional parameter that specifies which workflow associations should be canceled if you are not looking to cancel all of the workflow associations but just those of a specific name.
NB: The script contains a reference to a help function GetNestedCaml which I have defined in a separate post which can be found here.
As the script sample is quite large I suggest clicking the ‘view raw’ link at the bottom of the sample to view it.
As a developer my professional interests are technical and tend to be SharePoint focused. I've been working with SharePoint since 2009 and hope my posts will give back a little to the community that's supported me over this time. I'm also a keen runner (half-marathon) and passionate Brompton bicycle owner.
View all posts by Paul Ryan
4 thoughts on “Cancel all workflows in site collection efficiently”
you are missing the script from this blog
The script is in this post. It is posted using a github gist. If you can’t see it, it may be because you are viewing this post via an RSS reader.
When the script cancels the running workflows, does it put them into a completed status?
Unfortunately, this post is from 3.5 years ago and I don’t recall exactly how it behaves. You’ll have to give it a go and find out 🙂