Public/Workflow.ps1

#ExecuteWorkflowOnEntity
function Invoke-CrmRecordWorkflow{
# .ExternalHelp Campgemini.Xrm.Data.PowerShell.Help.xml
    [CmdletBinding()]
    PARAM(
        [parameter(Mandatory=$false)]
        [Microsoft.Xrm.Sdk.IOrganizationService]$conn,

        [parameter(Mandatory=$true, Position=1, ParameterSetName="CrmRecordWithWorkflowId")]
        [parameter(ParameterSetName="CrmRecordWithWorkflowName")]
        [PSObject]$CrmRecord,

        [parameter(Mandatory=$true, Position=1, ParameterSetName="CrmRecordIdWithWorkflowId")]
        [parameter(ParameterSetName="CrmRecordIdWithWorkflowName")]
        [Alias("Id", "StringId")]
        [string]$EntityId,

        [parameter(Mandatory=$true, Position=2, ParameterSetName="CrmRecordIdWithWorkflowName")]
        [parameter(ParameterSetName="CrmRecordWithWorkflowName")]
        [string]$WorkflowName, 

        [parameter(Mandatory=$true, Position=2, ParameterSetName="CrmRecordIdWithWorkflowId")]
        [parameter(ParameterSetName="CrmRecordWithWorkflowId")]
        [string]$WorkflowId
    )
    write-warning "$WorkflowId"
    $conn = VerifyCrmConnectionParam -conn $conn -pipelineValue ($PSBoundParameters.ContainsKey('conn'))
    
    if($CrmRecord -ne $null)
    {
        $fieldName = $CrmRecord.logicalname + "id"
        if(($CrmRecord|gm).Name.Contains("$fieldName")){
            $Id = $CrmRecord.($fieldName)
            Write-Verbose "RecordId set to: $Id"
        }
        elseif(($CrmRecord|gm).Name.Contains("activityid")){
            $Id = $CrmRecord.("activityid")
            Write-Verbose "RecordId set to: $Id"
        }
        else{
            throw "Cannot determine entities Id attribute"
        }
    }
    elseif($EntityId -ne $null)
    {
        $Id = [guid]::Parse($EntityId)
        Write-Verbose "RecordId set to: $Id"
    }

    try
    {
        $result = $null 
        if(-not [string]::IsNullOrEmpty($WorkflowName)){
            Write-Verbose "WorkflowName execution for workflow name: $WorkflowName"
            $fetch = @"
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
  <entity name="workflow">
    <attribute name="workflowid" />
    <attribute name="name" />
    <attribute name="primaryentity" />
    <attribute name="type" />
    <order attribute="name" descending="false" />
    <filter type="and">
      <condition attribute="name" operator="eq" value="$WorkflowName" />
      <condition attribute="statecode" operator="eq" value="1" />
      <condition attribute="type" operator="eq" value="1" />
      <condition attribute="rendererobjecttypecode" operator="null" />
      <condition attribute="category" operator="eq" value="0" />
    </filter>
  </entity>
</fetch>
"@

            $workflowResult = (Get-CrmRecordsByFetch -conn $conn -Fetch $fetch -TopCount 1)
            if($workflowResult.NextPage){
                throw "Duplicate workflow detected, try executing the workflow by its ID"
            }
            $WorkflowId = $workflowResult.CrmRecords[0].workflowid
        }

        if($WorkflowId -ne $null){
            Write-Verbose "WorkflowId execution for workflowid: $WorkflowId"
            $execWFReq = New-Object Microsoft.Crm.Sdk.Messages.ExecuteWorkflowRequest
            $execWFReq.EntityId = $Id
            $execWFReq.WorkflowId=$WorkflowId
            $result = $conn.Execute($execWFReq) 
        }
        else{ throw "Duplicate workflow detected, try executing the workflow by its ID"}
        if($result -eq $null)
        {
            throw $_.Exception
        }
    }
    catch
    {
        throw $_.Exception
    }
    return $result
}

function Get-CrmFailedWorkflows{
# .ExternalHelp Campgemini.Xrm.Data.PowerShell.Help.xml

    [CmdletBinding()]
    PARAM(
        [parameter(Mandatory=$false)]
        [Microsoft.Xrm.Sdk.IOrganizationService]$conn,
        [parameter(Mandatory=$false, Position=2)]
        [int]$TopCount,
        [parameter(Mandatory=$false, Position=3)]
        [int]$PageNumber,
        [parameter(Mandatory=$false, Position=4)]
        [string]$PageCookie,
        [parameter(Mandatory=$false, Position=5)]
        [switch]$AllRows
    )
    
    $conn = VerifyCrmConnectionParam -conn $conn -pipelineValue ($PSBoundParameters.ContainsKey('conn'))
    
    $fetch = @"
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false" no-lock="true">
              <entity name="asyncoperation">
                <attribute name="asyncoperationid" />
                <attribute name="name" />
                <attribute name="regardingobjectid" />
                <attribute name="operationtype" />
                <attribute name="statuscode" />
                <attribute name="ownerid" />
                <attribute name="startedon" />
                <attribute name="statecode" />
                <attribute name="workflowstagename" />
                <attribute name="postponeuntil" />
                <attribute name="owningextensionid" />
                <attribute name="modifiedon" />
                <attribute name="modifiedonbehalfby" />
                <attribute name="modifiedby" />
                <attribute name="messagename" />
                <attribute name="message" />
                <attribute name="friendlymessage" />
                <attribute name="errorcode" />
                <attribute name="createdon" />
                <attribute name="createdonbehalfby" />
                <attribute name="createdby" />
                <attribute name="completedon" />
                <order attribute="startedon" descending="true" />
                <filter type="and">
                  <condition attribute="recurrencestarttime" operator="null" />
                  <condition attribute="message" operator="not-null" />
                </filter>
              </entity>
            </fetch>
"@

    
    if($AllRows){
        $results = Get-CrmRecordsByFetch -conn $conn -Fetch $fetch -TopCount $TopCount -PageNumber $PageNumber -PageCookie $PagingCookie -AllRows 
    }
    else{
        $results = Get-CrmRecordsByFetch -conn $conn -Fetch $fetch -TopCount $TopCount -PageNumber $PageNumber -PageCookie $PagingCookie 
    }

    if($results.CrmRecords.Count -eq 0)
    {
        Write-Warning 'No failed worklfows found.'
    }
    else
    {
        return $results
    }
}