Functions/Client/New-CdsClient.ps1

<#
    .SYNOPSIS
    Initialize CrmserviceClient instance.
#>

function New-CdsClient {
    [CmdletBinding()]
    [OutputType("Microsoft.Xrm.Tooling.Connector.CrmServiceClient")]
    param
    (
        # https://docs.microsoft.com/fr-fr/powerapps/developer/common-data-service/xrm-tooling/use-connection-strings-xrm-tooling-connect
        [Parameter(Mandatory = $true)]
        [String]
        $ConnectionString
    )
    begin {   
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); 
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); 
    }    
    process {
        # Optimizations
        [System.Net.ServicePointManager]::Expect100Continue = $false;
        [System.Net.ServicePointManager]::UseNagleAlgorithm = $false;
        [System.Net.ServicePointManager]::DefaultConnectionLimit = 1000;
        [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;
    
        # Initialize CRM Client
        $xrmClient = $null;
        if ($Global:ConnectorsCache.ContainsKey($ConnectionString)) {
            $xrmClient = $Global:ConnectorsCache[$ConnectionString];
        }
        else {
            $xrmClient = Get-CrmConnection -ConnectionString $ConnectionString -ErrorAction Stop;
        }    
    
        if ($xrmClient.IsReady -eq $false) {
            throw $xrmClient.LastCrmError;
        }
    
        if ($Global:ConnectorsCache.ContainsKey($ConnectionString) -eq $false) {
            $Global:ConnectorsCache.Add($ConnectionString, $xrmClient);
        }

        $Global:XrmClient = $xrmClient;

        $url = $xrmClient.ConnectedOrgPublishedEndpoints["WebApplication"];
        $userId = $xrmClient.GetMyCrmUserId();
        # Store current settings to context as connection could be initiated with a simple connectionstring and we need thoose parameters for admin operations
        $userName = $ConnectionString | Out-CdsConnectionStringParameter -ParameterName "Username";
        if(-not $userName)
        {
            $userName = $userId;
        }
        $userPassword = $ConnectionString | Out-CdsConnectionStringParameter -ParameterName "Password";       

        $Global:CdsContext = New-CdsContext;
        $Global:CdsContext.UserId = $userId;
        if ($userName -and $userPassword) {
            $Global:CdsContext.Credentials = Set-CdsCredentials -Login $userName -Password $userPassword;
        }
        $Global:CdsContext.IsOnPremise = ($xrmClient.TenantId -eq [Guid]::Empty);
        $Global:CdsContext.IsOnline = (-not $Global:CdsContext.IsOnPremise);       

        $cdsConnection = New-CdsConnection;
        $cdsConnection.AuthType = $xrmClient.ActiveAuthenticationType.ToString();
        $cdsConnection.UserName = $userName;
        $cdsConnection.UserPassword = $userPassword; 
        if ($Global:CdsContext.IsOnline) {
            $cdsConnection.Region = Resolve-CdsRegionFromUrl -Url $url;
        }
        $Global:CdsContext.CurrentConnection = $cdsConnection;

        $cdsInstance = New-CdsInstance;
        $cdsInstance.Id = $xrmClient.ConnectedOrgId;
        $cdsInstance.DisplayName = $xrmClient.ConnectedOrgFriendlyName;
        $cdsInstance.UniqueName = $xrmClient.ConnectedOrgUniqueName;
        $cdsInstance.Url = $url;
        $cdsInstance.TenantId = $xrmClient.TenantId;
        $cdsInstance.EnviromentId = $xrmClient.EnvironmentId;
        if ($Global:CdsContext.IsOnline) {
            $cdsInstance.AdminApiUrl = Resolve-CdsApiUrl -Region $cdsConnection.Region;
        }
        $Global:CdsContext.CurrentInstance = $cdsInstance;

        Write-HostAndLog -Message "Connected to $($xrmClient.ConnectedOrgFriendlyName)! [Url = $url | User : $userName]" -ForegroundColor Yellow;        
        $xrmClient;
    }
    end {
        $StopWatch.Stop();
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

Export-ModuleMember -Function New-CdsClient -Alias *;