src/Plugins/Get-XrmPluginTraces.ps1

<#
    .SYNOPSIS
    Retrieve plugin traces.

    .DESCRIPTION
    Get latest plugin trace log from target instance.
    The traces are shown in a grid view (Out-GridView, Windows only), latest first: the rows selected there are returned with all their columns.

    .PARAMETER XrmClient
    Xrm connector initialized to target instance. Use latest one by default. (Dataverse ServiceClient)

    .PARAMETER ErrorsOnly
    If true, filter results to return only errors (traces with exception details). (Default: false = all traces)

    .PARAMETER Take
    Specify number of items to retrieve. (Default : 50)

    .OUTPUTS
    PSCustomObject[]. The plugintracelog rows selected in the grid view.

    .EXAMPLE
    $xrmClient = New-XrmClient -ConnectionString $connectionString;
    $traces = $xrmClient | Get-XrmPluginTraces -ErrorsOnly $true -Take 20;
    $traces | Select-Object typename, messagename, exceptiondetails;

    .LINK
    https://github.com/AymericM78/PowerDataOps/blob/main/documentation/commands/Get-XrmPluginTraces.md
#>

function Get-XrmPluginTraces {
    [CmdletBinding()]    
    [OutputType([PSCustomObject[]])]
    param
    (        
        [Parameter(Mandatory = $false, ValueFromPipeline)]
        [Microsoft.PowerPlatform.Dataverse.Client.ServiceClient]
        $XrmClient = $Global:XrmClient,

        [Parameter(Mandatory = $false)]
        [bool]
        $ErrorsOnly = $false,

        [Parameter(Mandatory = $false)]
        [int]
        $Take = 50
    )
    begin {
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters);       
    }    
    process {
        
        $queryTraces = New-XrmQueryExpression -LogicalName "plugintracelog" -Columns *;
        $queryTraces = $queryTraces | Add-XrmQueryOrder -Field "performanceexecutionstarttime" -OrderType Descending;
        if ($ErrorsOnly) {
            $queryTraces = $queryTraces | Add-XrmQueryCondition -Field "exceptiondetails" -Condition NotNull;
        }
        $queryTraces.TopCount = $Take;
        $traces = $XrmClient | Get-XrmMultipleRecords -Query $queryTraces;

        $selectedTraces = $traces | Select-Object "performanceexecutionstarttime", "performanceexecutionduration", "operationtype", "typename", "correlationid", "depth", "mode", "messagename", "primaryentity", "plugintracelogid"  | Out-GridView -OutputMode Multiple;

        $selectedTraces | ForEach-Object {
            $fullTrace = $traces | Where-Object -Property "plugintracelogid" -EQ -Value $_.plugintracelogid;
            $fullTrace;
        }
    }
    end {
        $StopWatch.Stop();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

Export-ModuleMember -Function Get-XrmPluginTraces -Alias *;