Get workflow inventory from SharePoint online using PowerShell CSOM

2 best way to get workflow inventory from SharePoint online using PowerShell CSOM

One comment

Loading

In this tutorial, we will learn about how we can get workflow inventory from the SharePoint Online tenant using PowerShell CSOM and PnP PowerShell. This script will scan through all the sites in a tenant and export all workflows associated with the lists into a CSV file, which will give a consolidated workflow report from the SharePoint Online tenant.

Get workflow inventory from SharePoint Online: Export all workflows from SharePoint Online Tenant using PowerShell CSOM

Using the below PowerShell CSOM code, we can export or get all workflows from the SharePoint Online tenant:

Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking
#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"
    cls
    $fileName = "Tenant_workflow_Report" #'yyyyMMddhhmm   yyyyMMdd
    $enddate = (Get-Date).tostring("yyyyMMddhhmmss")
    #$filename =  $enddate + '_VMReport.doc'  
    $logFileName = $fileName +"_"+ $enddate+"_Log.txt"   
    $invocation = (Get-Variable MyInvocation).Value  
    $directoryPath = Split-Path $invocation.MyCommand.Path

     $directoryPathForLog=$directoryPath+"\"+"LogFiles"
     if(!(Test-Path -path $directoryPathForLog))  
        {  
            New-Item -ItemType directory -Path $directoryPathForLog
            #Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
        }   


#$logPath = $directoryPath + "\" + $logFileName 
$logPath = $directoryPathForLog + "\" + $logFileName   
$isLogFileCreated = $False 



#DLL location

$directoryPathForDLL=$directoryPath+"\"+"Dependency Files"
if(!(Test-Path -path $directoryPathForDLL))  
        {  
            New-Item -ItemType directory -Path $directoryPathForDLL
            #Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
        } 

#DLL location

$clientDLL=$directoryPathForDLL+"\"+"Microsoft.SharePoint.Client.dll"
$clientDLLRuntime=$directoryPathForDLL+"\"+"Microsoft.SharePoint.Client.dll"

Add-Type -Path $clientDLL
Add-Type -Path $clientDLLRuntime


#File Download location

$directoryPathForFileDownloadLocation=$directoryPath+"\"+"Download Workflow Details"
if(!(Test-Path -path $directoryPathForFileDownloadLocation))  
        {  
            New-Item -ItemType directory -Path $directoryPathForFileDownloadLocation
            #Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
        } 

#File Download location



function Write-Log([string]$logMsg)  
{   
    if(!$isLogFileCreated){   
        Write-Host "Creating Log File..."   
        if(!(Test-Path -path $directoryPath))  
        {  
            Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
        }   
        else   
        {   
            $script:isLogFileCreated = $True   
            Write-Host "Log File ($logFileName) Created..."   
            [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)   
            Add-Content -Path $logPath -Value $logMessage   
        }   
    }   
    else   
    {   
        [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)   
        Add-Content -Path $logPath -Value $logMessage   
    }   
} 

#Object array to hold workflow details.

$WorkflowDetailsForSPOSite=@()

#The below function will read all workflows from a site and return the array output. 
 
Function Get-WorkflowAssociationsDeatilsForEachSiteInTenant()
{
     
    param
    (
        [Parameter(Mandatory=$true)] [string] $SPOSiteURL,              
        [Parameter(Mandatory=$true)] [string] $UserName,
        [Parameter(Mandatory=$true)] [string] $Password
    )
    Try 
    {
        $securePassword= $Password | ConvertTo-SecureString -AsPlainText -Force  
        #Setup the Context
        $context = New-Object Microsoft.SharePoint.Client.ClientContext($SPOSiteURL)
        $context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $securePassword)

       
        $web = $context.Web
        $context.Load($web)
        $context.Load($web.Webs)     
   
        $context.executeQuery()

        #Check if any sub site is available in the site.

        if ($web.Webs.Count -ne 0)
        {
            foreach ($subweb in $web.Webs)
            {
                
                Get-WorkflowAssociationsDeatilsForEachSiteInTenant -SPOSiteURL $subweb.url -UserName $userName -Password $password
            }
        }
 
        #Loading all lists for the particular site.
        $context.Load($web.Lists)
        $context.ExecuteQuery() 
 
        foreach($list in $web.Lists)
         {     
            $context.Load($list.WorkflowAssociations)   
            $context.ExecuteQuery() 
 
            foreach($wfAssociation in $list.WorkflowAssociations)
             {
                if($wfAssociation.name -notlike "*Previous Version*")
                    {
                    $row=new-object PSObject
                    add-Member -inputObject $row -memberType NoteProperty -name "Site Title" -Value $web.Title
                    add-Member -inputObject $row -memberType NoteProperty -name "Site URL" -Value $web.Url
                    add-Member -inputObject $row -memberType NoteProperty -name "List Title" -Value $list.Title
                    add-Member -inputObject $row -memberType NoteProperty -name "Workflow Name" -Value $wfAssociation.Name
                    add-Member -inputObject $row -memberType NoteProperty -name "Workflow Type" -Value "SharePoint List"
                    $WorkflowDetailsForSPOSite+=$row
                }
            }
        }
        return $WorkflowDetailsForSPOSite   
          

    }
    catch
    {
      write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
      $ErrorMessage = $_.Exception.Message +"in exporting workflow details!:" 
      Write-Host $ErrorMessage -BackgroundColor Red
      Write-Log $ErrorMessage       

    }
    
}

#Parameters
#$siteURL="https://globalsharepoint2019.sharepoint.com/sites/ModernTeamSiteTestByPnP"
$adminUrl = "https://globalsharepoint2019-admin.sharepoint.com/"
$downloadLocation=$directoryPathForFileDownloadLocation +"\"+ "SPOTenantWorkflowReport.csv"
$userName = "YourSPOUserName"
$password = "YourSPOPassWord"
$securePassword= $password | ConvertTo-SecureString -AsPlainText -Force

#Parameters ends here.

$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $SecurePassword


#Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking
#Retrieve all site collection infos
#Connect-SPOService -Url $AdminUrl -Credential $Credentials
#$sites = Get-SPOSite 


Connect-PnPOnline -Url $adminUrl -Credentials $Credentials

$allTenantSites=Get-PnPTenantSite

#Get-WorkflowAssociationsDeatilsForEachSiteInTenant -SPOSiteURL $siteURL -UserName $userName -Password $password | Export-Csv $downloadLocation

if($allTenantSites.Count -gt 0)
{

$finalWorkflowReport =foreach($oneSite in $allTenantSites)
{

Get-WorkflowAssociationsDeatilsForEachSiteInTenant -SPOSiteURL $oneSite.URL -UserName $userName -Password $password

}
$finalWorkflowReport | Export-Csv $downloadLocation -NoTypeInformation

}

Write-host "All workflows have been exported Successfully from the SharePoint Online Tenant." -BackgroundColor Green

Workflow Inventory from SharePoint Online: Description of the above code:

  • We must use the “Get-PnPTenantSite” to get all sites from the tenant, the other command “Get-PnPSite“, if we use this, will give only the tenant admin site URL, like below:
Get-PnPSite in SharePoint Online
Get-PnPSite in SharePoint Online
  • Similarly, in order to get all sites from the tenant, we can use the “Get-SPOSite” command as well. However, if you have a .net framework mismatch version installed in your PowerShell – this command will not work, we will get an error like “Connect-SPOService : Method not found: ‘!!0[] System.Array.Empty()‘”
Connect-SPOService : Method not found: '!!0[] System.Array.Empty()'
Connect-SPOService : Method not found: ‘!!0[] System.Array.Empty()’
  • If we use the above code as is this will export all workflows from the tenant. However, if we want to export all workflows from a particular site we can comment the for each loop and just we need to call the function”Get-WorkflowAssociationsDeatilsForEachSiteInTenant” as below:
    Get-WorkflowAssociationsDeatilsForEachSiteInTenant -SPOSiteURL $siteURL -UserName $userName -Password $password | Export-Csv $downloadLocation
    

Demo: Get workflow inventory from SharePoint Online (export workflow)

Now, let’s execute the above script.

Get all workflows from SharePoint Online Tenant using PowerShell CSOM
Get all workflows from SharePoint Online Tenant using PowerShell CSOM

Demo Result: Get workflow inventory from SharePoint Online (export workflow)

After the successful execution of the script, a CSV file with the name “SPOTenantWorkflowReport.csv” will be created in the script location directory – however, you can change the download location to your desired location.

Get All Workflows Report from SharePoint Online CSV Report location
Get All Workflows Report from SharePoint Online CSV Report location

Now, let’s look at all workflows exported CSV reports.

CSV Report - Get all workflows from SharePoint Online Tenant using PowerShell CSOM
CSV Report – Get all workflows from SharePoint Online Tenant using PowerShell CSOM

We can see in the CSV report, that all workflows from the SharePoint Online tenant have been exported.

Prerequisites to execute the above script: Get workflow inventory from SharePoint

Need to place the below two DLLs in your script directory “Dependency Files” folder as below:

DownloadDocumentsUsingPowerShellCSOM5

Install PnP PowerShell:

To install the “SharePointPnPPowerShellOnline” we need to run the below PowerShell command which will install PowerShell Package Management and then install the PowerShell Modules from the PowerShell Gallery.

(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/sharepoint/PnP-PowerShell/master/Samples/Modules.Install/Install-SharePointPnPPowerShell.ps1')

 

Change the value of the variables in the parameters section like below:

#Parameters
#$siteURL="https://globalsharepoint2019.sharepoint.com/sites/ModernTeamSiteTestByPnP"
$adminUrl = "Your SPO Admin URL Like - https://globalsharepoint2019-admin.sharepoint.com/"
$downloadLocation=$directoryPathForFileDownloadLocation +"\"+ "SPOTenantWorkflowReport.csv"
$userName = "YourSPOUserName"
$password = "YourSPOPassWord"
$securePassword= $password | ConvertTo-SecureString -AsPlainText -Force
#Parameters ends here.

Get workflow inventory using the SharePoint modernization scanner tool

Using the SharePoint modernization scanner tool also, we can export the workflow inventory from SharePoint Online. Learn more about the SharePoint modernization scanner tool here – Getting started with the SharePoint modernization scanner.

Summary: Get workflow inventory from SharePoint Online

Hence, in this tutorial, we have learned the below topics:

  • How to export workflow from SharePoint Online using PowerShell CSOM and PnP.
  • How to use “Get-PnPTenantSite” and “Get-PnPSite”.
  • What is the difference between Get-PnPTenantSite and Get-PnPSite?
  • How to get a consolidated Workflow Report From SharePoint Online Tenant.
  • How to use “Connect-SPOService” and “Get-SPOSite”
  • How to fix the error “Connect-SPOService : Method not found: ‘!!0[] System.Array.Empty()'”
  • How to get all workflows from SharePoint online tenant.
  • How to export all workflows from SharePoint online to a CSV file.
  • How to export all SharePoint Online sites to a CSV file using PnP PowerShell.

See Also: SharePoint Online tutorial

You may also like the below SharePoint Online tutorials:

Download SharePoint Online PDF Book

Download SharePoint Online & Office 365 Administration eBook

Buy the premium version of SharePoint Online & Office 365 administration eBook from here:



Buy SharePoint Online & Office 365 Administration eBook


 

Get the free demo PDF eBook from here:

FREE DOWNLOAD

Send download link to:

Subscribe to get exclusive content and recommendations every month. You can unsubscribe anytime.

About Post Author

1 comments on “2 best way to get workflow inventory from SharePoint online using PowerShell CSOM”

Do you have a better solution or question on this topic? Please leave a comment