Tuesday, September 16, 2014

SharePoint powershell to cancel workflows

I got stuck into a situation where the workflows in SharePoint were stuck during the "In Progress" stage, and there was no way to cancel the workflow from the UI.

After googling around, I found a simple powershell solution and adapted it slightly to suit my needs.

The concept is very simple - Load the site, load the library, and either traverse all items, or retrieve a single item based on the ID. For that item, loop through the workflows and cancel it!



#Enter the website URL
$web = Get-SPWeb "http://sharepoint"
$web.AllowUnsafeUpdates = $true
#Enter the List or Library Name
$list = $web.Lists["Test"]
#Either identify the Item by ID, or loop through the list items by un-commenting the foreach loop
$listItem = $list.GetItemById(641);
#foreach ($listItem in $list.Items)
#{
 foreach ($workflow in $listItem.Workflows)
 {
  #Disregard Completed Workflows
  if(($listItem.Workflows | where {$_.InternalState -ne "Completed"}) -ne $null)
  {
   #Cancel Workflows       
   [Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($workflow);     
   write-output "Workflow cancelled for : " $listItem.Title; 
  }
 }
#}
$web.Dispose();

No comments:

Related Posts Plugin for WordPress, Blogger...