SharePoint Online: Start Workflow on All Items in a List using PowerShell

Requirement: Run Workflow in SharePoint Online using PowerShell

SharePoint Online: PowerShell to Start Workflow
This PowerShell script starts given workflow on all items in a SharePoint Online list.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.WorkflowServices.dll"

#Set Parameters
$SiteURL="https://crescenttech.sharepoint.com/Sites/PMO"
$ListName ="Project Tasks"
$WorkflowName ="Send Approval Email"

#Get Credentials to connect
$Cred= Get-Credential

Try{
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
    
    #Get the Web, List and List Items Object
    $Web = $Ctx.Web
    $Ctx.Load($Web)
    $List = $Web.Lists.GetByTitle($ListName)
    $ListItems = $List.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())
    $Ctx.Load($List)
    $Ctx.Load($ListItems)
    $Ctx.ExecuteQuery()

    #Initialize Workflow Manager and other related objects
    $WorkflowServicesManager = New-Object Microsoft.SharePoint.Client.WorkflowServices.WorkflowServicesManager($Ctx, $Web)
    $WorkflowSubscriptionService = $workflowServicesManager.GetWorkflowSubscriptionService()
    $WorkflowInstanceService = $WorkflowServicesManager.GetWorkflowInstanceService() 
    $WorkflowAssociations = $WorkflowSubscriptionService.EnumerateSubscriptionsByList($List.Id)
    $Ctx.Load($WorkflowAssociations)
    $Ctx.ExecuteQuery()

    #Get the Target workflow to Run
    $WorkflowAssociation = $WorkflowAssociations | Where {$_.Name -eq $WorkflowName}
  
    #Start Workflow on each List Item
    ForEach($ListItem in $ListItems)
    {
        #sharepoint online powershell start workflow        
        $Dict = New-Object 'System.Collections.Generic.Dictionary[System.String,System.Object]'
        $Action = $WorkflowInstanceService.StartWorkflowOnListItem($WorkflowAssociation, $ListItem.Id, $Dict)
    }
    $Ctx.ExecuteQuery()
}
Catch {
Write-host -f Red "Error:" $_.Exception.Message
}
This PowerShell runs workflow in each item of a list in SharePoint Online.
SharePoint Online: Start Workflow on All Items in a List using PowerShell SharePoint Online: Start Workflow on All Items in a List using PowerShell Reviewed by Salaudeen Rajack on May 07, 2018 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.