src/Client/Invoke-XrmRequest.ps1

<#
    .SYNOPSIS
    Execute Organization Request.

    .Description
    Send request to Microsoft Dataverse for execution.
    Supports -WhatIf and -Confirm for the requests that write: a read request (Retrieve*, WhoAmI, Export*...) always runs, a write request runs only if ShouldProcess allows it (with -WhatIf, it is skipped and $null is returned).
    Every write of the module goes through this cmdlet, so -WhatIf given to any module cmdlet reaches the writes it makes.

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

    .PARAMETER Request
    Organization request to execute.

    .PARAMETER Async
    Indicates if request should be run in background. Request must supports asynchronous execution. (Default: false = run synchronously)

    .PARAMETER TimeoutInMinutes
    Maximum wait for the response, for a long synchronous request. The request is sent through a clone of the connection created with this timeout (a ServiceClient keeps the timeout it was created with). Prefer the asynchronous message when the platform has one (ProvisionLanguageAsync, PublishAllXmlAsync...), with Watch-XrmAsynchOperation. (Default: the timeout of the connection, 4 minutes unless New-XrmClient or Set-XrmClientTimeout changed it)

    .OUTPUTS
    Microsoft.Xrm.Sdk.OrganizationResponse. The response ($null when a write is skipped by -WhatIf).

    .EXAMPLE
    $response = $xrmClient | Invoke-XrmRequest -Request (New-XrmRequest -Name "WhoAmI");

    .EXAMPLE
    # Long synchronous request
    $response = $xrmClient | Invoke-XrmRequest -Request $request -TimeoutInMinutes 30;

    .EXAMPLE
    # Show what would be written, without writing
    $xrmClient | Invoke-XrmRequest -Request $deleteRequest -WhatIf;

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

function Invoke-XrmRequest {
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    [OutputType([Microsoft.Xrm.Sdk.OrganizationResponse])]
    param
    (
        [Parameter(Mandatory = $false, ValueFromPipeline)]
        [Microsoft.PowerPlatform.Dataverse.Client.ServiceClient]
        $XrmClient = $Global:XrmClient,

        [Parameter(Mandatory = $true)]
        [Microsoft.Xrm.Sdk.OrganizationRequest]
        $Request,

        [Parameter(Mandatory = $false)]
        [Switch]
        $Async,

        [Parameter(Mandatory = $false)]
        [ValidateRange(1, 1440)]
        [int]
        $TimeoutInMinutes
    )
    begin {
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters);
    }
    process {

        if ($Async) {
            $innerRequest = $Request
            $Request = New-Object -TypeName Microsoft.Xrm.Sdk.Messages.ExecuteAsyncRequest;
            $Request.Request = $innerRequest;
        }

        if (-not (Test-XrmReadOnlyRequestInternal -Request $Request)) {
            $target = $Request.RequestName;
            if ($Request.Parameters.Contains("Target")) {
                $targetValue = $Request.Parameters["Target"];
                if ($targetValue -is [Microsoft.Xrm.Sdk.Entity] -or $targetValue -is [Microsoft.Xrm.Sdk.EntityReference]) {
                    $target = if ($targetValue.Id -eq [Guid]::Empty) { "$($targetValue.LogicalName) (new)" } else { "$($targetValue.LogicalName) $($targetValue.Id)" };
                }
            }
            elseif ($Request.Parameters.Contains("Requests")) {
                $target = "$($Request.Parameters["Requests"].Count) requests";
            }
            else {
                # Metadata and solution messages name their subject in other parameters
                $subject = @("EntityLogicalName", "LogicalName", "SchemaName", "Name", "UniqueName", "SolutionUniqueName", "ComponentId", "JobName") | Where-Object { $Request.Parameters.Contains($_) -and $null -ne $Request.Parameters[$_] } | ForEach-Object { "$_ = $($Request.Parameters[$_])" };
                if ($subject) {
                    $target = ($subject -join ", ");
                }
            }
            if (-not $PSCmdlet.ShouldProcess($target, $Request.RequestName)) {
                return $null;
            }
        }

        # The timeout of a ServiceClient is fixed when it connects: a clone made after raising the
        # static MaxConnectionTimeout gets the longer one, the caller's client keeps its own
        $requestClient = $XrmClient;
        $longTimeoutClient = $null;
        if ($PSBoundParameters.ContainsKey('TimeoutInMinutes')) {
            $previousTimeout = [Microsoft.PowerPlatform.Dataverse.Client.ServiceClient]::MaxConnectionTimeout;
            try {
                [Microsoft.PowerPlatform.Dataverse.Client.ServiceClient]::MaxConnectionTimeout = [TimeSpan]::FromMinutes($TimeoutInMinutes);
                $longTimeoutClient = $XrmClient.Clone();
                $requestClient = $longTimeoutClient;
            }
            catch {
                throw "Cannot open the connection with a timeout of $TimeoutInMinutes minute(s), request $($Request.RequestName) not sent: $($_.Exception.Message)";
            }
            finally {
                [Microsoft.PowerPlatform.Dataverse.Client.ServiceClient]::MaxConnectionTimeout = $previousTimeout;
            }
        }

        try {
            $response = Protect-XrmCommand -ScriptBlock { $requestClient.Execute($Request) };
            $response;
        }
        finally {
            if ($longTimeoutClient) {
                $longTimeoutClient.Dispose();
            }
        }
    }
    end {
        $StopWatch.Stop();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }
}

Export-ModuleMember -Function Invoke-XrmRequest -Alias *;