SharePoint 2013 – Workflow Management – Starting a workflow using Powershell

Had a simple task of creating a Powershell script that would be able to start a SharePoint workflow. Shouldn’t be too much a problem, I mean just get the web, get the list, find the associated workflows and start the right one using Powershell. How hard can it be?
Failing really short on examples on the web I had help from great colleagues again, puzzled together the below. The below code will start a specific workflow on all items within a designated list. The below should give the foundation to work with other management type tasks for SharePoint Workflows; Start, Start, Cancel etc.
I might update with additional examples, if needed 🙂

The Code

$sourceWebURL = '<URL>'
$sourceListName = '<List Name>'
$TargetWorkflow = '<Workflow Name>'
$spSourceWeb = Get-SPWeb $sourceWebURL
$spSourceList = $spSourceWeb.Lists[$sourceListName]

#Getting a Workflow manager object to work with.
$wfm = New-object Microsoft.SharePoint.WorkflowServices.WorkflowServicesManager($spSourceweb)
#Getting the subscriptions
$sub = $wfm.GetWorkflowSubscriptionService()
#Getting the specific workflow within the list of subscriptions on the specific list. (SP2010 associated workflows basically)
$WF = $sub.EnumerateSubscriptionsByList($spSourcelist.ID) | Where-Object {$_.Name -eq "$TargetWorkflow"}
#Getting a Workflow instance in order to perform my commands.
$wfis=$wfm.GetWorkflowInstanceService()

Foreach($item in $spSourceList){
	#Creating the dictonary object I need to parse into StartWorkflow. This could be most other workflow commands.
	$object = New-Object 'system.collections.generic.dictionary[string,object]'
	$object.Add("WorkflowStart", "StartWorkflow");
	$wfis.StartWorkflowOnListItem($WF, $item.ID, $object)

References
Microsoft.SharePoint.Client.WorkflowServices namespace
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.workflowservices%28v=office.15%29.aspx

Additional credit
Frej Laursen, Joachim Bach & Per Jakobsen.

Advertisements

3 comments

  1. Hi,
    Thanks for this information. I have some workflows canceled in SharePoint 2013. I want to restart all the canceled workflow. Can you give me some ideas how to restart cancelled workflows

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s