src/Solutions/Customization/Views/Test-XrmView.ps1

<#
    .SYNOPSIS
    Validate a saved query (view) in Microsoft Dataverse.

    .DESCRIPTION
    Check if a saved query (view) definition is valid using the ValidateSavedQuery SDK action.
    The FetchXml and the type of the view are read first, unpublished changes included. An invalid definition, or an unknown view, raises an error.

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

    .PARAMETER ViewId
    Guid of the savedquery record to validate.

    .OUTPUTS
    Microsoft.Xrm.Sdk.OrganizationResponse. The ValidateSavedQuery response.

    .EXAMPLE
    $result = Test-XrmView -ViewId $viewId;

    .LINK
    https://github.com/AymericM78/PowerDataOps/blob/main/documentation/commands/Test-XrmView.md

    .LINK
    https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/validatesavedquery
#>

function Test-XrmView {
    [CmdletBinding()]
    [OutputType([Microsoft.Xrm.Sdk.OrganizationResponse])]
    param
    (
        [Parameter(Mandatory = $false, ValueFromPipeline)]
        [Microsoft.PowerPlatform.Dataverse.Client.ServiceClient]
        $XrmClient = $Global:XrmClient,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [Guid]
        $ViewId
    )
    begin {
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters);
    }
    process {
        $viewQuery = New-XrmQueryExpression -LogicalName "savedquery" -Columns "fetchxml", "querytype";
        $viewQuery = $viewQuery | Add-XrmQueryCondition -Field "savedqueryid" -Condition Equal -Values $ViewId;
        $view = $XrmClient | Get-XrmMultipleComponents -Query $viewQuery -Unpublished;
        if (-not $view) {
            throw "View '$ViewId' not found.";
        }

        $request = New-XrmRequest -Name "ValidateSavedQuery";
        $request | Add-XrmRequestParameter -Name "FetchXml" -Value ($view | Get-XrmAttributeValue -Name "fetchxml") | Out-Null;
        $request | Add-XrmRequestParameter -Name "QueryType" -Value ($view | Get-XrmAttributeValue -Name "querytype") | Out-Null;

        $response = $XrmClient | Invoke-XrmRequest -Request $request;
        $response;
    }
    end {
        $StopWatch.Stop();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }
}

Export-ModuleMember -Function Test-XrmView -Alias *;