Tuesday, January 5, 2016

Starting SharePoint Workflows with PowerShell

PowerShell is often used for many activities related to SharePoint. For any quick fixes around can be handled easily with PowerShell. Its no doubt Workflows are a vital part of SharePoint and with SharePoint 2013, they are not anymore in the SharePoint. 

Another important thing is that we often run SharePoint 2013 Management Shell as the administrator. But it is recommended not to use a SharePoint service account for running workflows. Well, it does not work. 

This makes starting a workflow tricky. We can get over with this through two tricky ways. One is granting another user with a Shell Admin permissions. But I would not recommend that. So the answer is simply impersonating a user. 

The following script will allow you to start a workflow without much issue if you have configured and provisioned Workflow Service Application for SharePoint 2013 onward correctly. 

I have used a few variables here. 

$webSiteUrl = "HTTP://SITEURL/"
The site which we need to start the workflow.

$impersonateUserName = "DOMAIN\USERNAME"
The user who is not a service account that will be used to start the workflow.

$listName = "LIST NAME"
The list name where the workflow is attached.

$workflowName = "WORKFLOW NAME"
The name of the workflow we need to start.

$itemId= 1
Item id of the list item. This can be taken by looping through the list as well. But for the simplicity, I have kept it as a constant.

The complete code is as follows.

$webSiteUrl = "HTTP://SITEURL/"
$impersonateUserName = "DOMAIN\USERNAME"
$listName = "LIST NAME"
$workflowName = "WORKFLOW NAME"
$itemId= 1;

$webSite = get-spweb $webSiteUrl

$token = $impersonationUser.UserToken;
$impWebObj= New-Object Microsoft.SharePoint.SPSite($webSite.Url, $token);
$imperWeb = $impWebObj.OpenWeb();

$list = $imperWeb.lists | where {$_.title -eq $listName}

$workflowServiceManager = New-object Microsoft.SharePoint.WorkflowServices.WorkflowServicesManager($imperWeb)
$sub = $workflowServiceManager.GetWorkflowSubscriptionService()
$itemWorkflow = $sub.EnumerateSubscriptionsByList($list.ID) | Where-Object {$_.Name -eq $workflowName}
$wfis = $workflowServiceManager.GetWorkflowInstanceService()
$object = New-Object 'system.collections.generic.dictionary[string,object]'
$object.Add("WorkflowStart", "StartWorkflow");
$wfis.StartWorkflowOnListItem($itemWorkflow, $itemId, $object)

No comments:

Post a Comment