Let’s admit it.  Sometimes things just go wrong and you need an easy or straight forward way of cleaning it up and starting over again.  An example of this happened to me the other day where I had a bad workflow that went unnoticed and started suspending.  By the time it was noticed there were about 50+ suspended workflows (it was an active list).  So after stopping the workflow I started working through cleaning it up and thought there has to be a way to terminate SharePoint 2013 workflows with PowerShell.  Turns out I could do it.  Here’s how:

Terminate SharePoint 2013 Workflows with PowerShell

Terminating a 2013 workflow is different than a 2010 workflow.  I’ll cover that in a future blog.  To start off you need to get an instance of the workflow manager service and then  you just need to loop through every item of the list (or a subset if you want to do it that way) and check to see if there is any workflows.  If there are you check the instances of each and determine if they need to be canceled.  Here’s the code:

if ( (Get-PSSnapin -Name "Microsoft.SharePoint.Powershell" -ErrorAction SilentlyContinue) -eq $null )
    Add-PsSnapin Microsoft.SharePoint.Powershell

$siteURL = "<Site URL>";
$listName = "<ListName>";

$spWeb = Get-SPWeb $siteURL;
$spList = $spWeb.Lists[$listName];
$spListItems = $spList.Items;

#Get the Workflow Manager object and then the instance of the Manager
$wfMgr = New-object Microsoft.SharePoint.WorkflowServices.WorkflowServicesManager($spWeb);
$wfInstanceSvc = $wfMgr.GetWorkflowInstanceService();

foreach($spListItem in $spListItems)
    #Get a list of workflow instances running for the item in the list
    $wfInstances = $wfInstanceSvc.EnumerateInstancesForListItem($spList.ID, $spListItem.ID);
    foreach($wfInstance in $wfInstances)
        #Check to see if the instance is suspended.  If so, terminate it.
        if($wfInstance.Status -eq "Suspended")
            write-host("Terminating instances for list item: {0}" -f $spListItem.ID);   

This comes in handy for other situations too.  Say for instance you were doing some sort of bulk insert of items and you forgot temporarily turn off a workflow.  Modifying “if($wfInstance.Status -eq “Suspended”)” to “if($wfInstance.Status -eq “Started”)” will allow you to stop all those errant workflows you started by accident.

Hope this is helpful.


Thanks for reading!