Wednesday, October 12, 2016

SharePoint Online - Get workflow status in List Item using PowerShell

Requirement was for SharePoint online tenant to get the workflow status in list item.
I choose to write quick PowerShell script using CSOM to achieve this.


 [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")  
 [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")  
 Function Get-SPOCredentials([string]$UserName,[string]$Password)  
 {  
   if([string]::IsNullOrEmpty($Password)) {  
    $SecurePassword = Read-Host -Prompt "Enter password" -AsSecureString   
   }  
   else {  
    $SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force  
   }  
   return New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)  
 }  
  Function GetWorkflowStatus([Microsoft.SharePoint.Client.List]$list,[int]$listItemId, [string]$workflowName)  
  {  
    $context = $list.Context  
    $listItem = $list.GetItemById($listItemId)  
    $context.Load($listItem.FieldValuesAsHtml)  
    $workflowStatusField = $listItem.ParentList.Fields.GetByTitle($workflowName)  
    $context.Load($workflowStatusField)  
    $context.ExecuteQuery()  
    if ($listItem.FieldValuesAsHtml[$workflowStatusField.StaticName] -ne $null)  
    {  
      $statusValue = $listItem.FieldValuesAsHtml[$workflowStatusField.StaticName]  
      return $statusValue;  
    }  
    return $null  
  }  
 $UserName = "username@yourtenant.onmicrosoft.com"  
 $Password = Read-Host -Prompt "Enter the password"    
 $WebUrl = "https://yourtenant.sharepoint.com/"  
 $ListTitle = "MySPList"  
 $ListItemId = 1  
 $WorkflowTitle = "Approval"  
 $Context = New-Object Microsoft.SharePoint.Client.ClientContext($WebUrl)  
 $Context.Credentials = Get-SPOCredentials -UserName $UserName -Password $Password  
 $list = $Context.Web.Lists.GetByTitle($ListTitle)  
 $statusValue = GetWorkflowStatus -list $list -listItemId $ListItemId -workflowName $workflowTitle  
 $Context.Dispose()  

Hope this handy script will save your time!

No comments:

Post a Comment