src/SQL/Invoke-XrmSqlCommand.ps1

<#
    .SYNOPSIS
    Connect to TDS endpoint.
    
    .DESCRIPTION
    Specify connection parameters to run SQL commands thru TDS Endpoint.
    The statement runs on the TDS endpoint of the instance with the access token of the connection. The TDS endpoint is read-only (SELECT) and must be enabled (see Enable-XrmTdsEndpoint).

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

    .PARAMETER Command
    SQL Statement

    .PARAMETER IgnoreDbNull
    Leave out the columns whose value is NULL instead of returning them with a DBNull value. (Default: False)

    .OUTPUTS
    PSCustomObject. One object per row, with one property per column (in no particular order).

    .EXAMPLE
    $accounts = Invoke-XrmSqlCommand -XrmClient $xrmClient -Command "SELECT TOP 10 name, revenue FROM account ORDER BY revenue DESC" -IgnoreDbNull;

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

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

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $Command,

        [Parameter(Mandatory = $false)]
        [Switch]
        $IgnoreDbNull = $false
    )
    begin {   
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); 
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters);      
        if(-not $Global:XrmClient){
            throw "Not connected to Dataverse instance (New-XrmClient)";
        }
        Assert-XrmTdsEndpointEnabled -XrmClient $XrmClient;  
    }    
    process {            
        $sqlConnectionString = "server=$($XrmClient.ConnectedOrgUriActual.Host)";

        $connection = new-object System.Data.SqlClient.SQLConnection($sqlConnectionString);
        $connection.AccessToken = $XrmClient.CurrentAccessToken;
        $cmd = new-object System.Data.SqlClient.SqlCommand($Command, $connection);

        $connection.Open();
        $reader = $cmd.ExecuteReader();

        [System.Collections.ArrayList]$results = @();
        while ($reader.Read()) {
            $hash = @{};            
            for ($i = 0; $i -lt $reader.FieldCount; $i++) {
                $value = $reader.GetValue($i);
                if ($IgnoreDbNull -and $value -eq [DBNull]::Value) {
                    continue;
                }
                $hash[$reader.GetName($i)] = $value;
            }
            $object = [pscustomobject]$hash;
            $results.Add($object) | Out-Null;
        }
        $connection.Close();

        $results;
    }
    end {
        $StopWatch.Stop();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

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