Functions/Client/New-CdsClient.ps1

<#
    .SYNOPSIS
    Initialize CrmserviceClient instance.
#>

function New-CdsClient {
    [CmdletBinding()]
    [OutputType("Microsoft.Xrm.Tooling.Connector.CrmServiceClient")]
    param
    (
        [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
        if (-not($ConnectionString)) {
            $ConnectionString = Get-CrmConnectionString;
        }
    
        $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;

        $crmLogin = $xrmClient.OrganizationServiceProxy.ClientCredentials.UserName.UserName;
        $crmUrl = $xrmClient.ConnectedOrgPublishedEndpoints["WebApplication"];
        Write-HostAndLog -Message "Connected to $($xrmClient.ConnectedOrgFriendlyName)! [Url = $crmUrl | User : $crmLogin]" -ForegroundColor Yellow;

        # Store current settings to context as connection could be initiated with a simple connectionstring and we need thoose parameters for admin operations
        $Global:CdsContext = New-CdsContext;
        $Global:CdsContext.Url = $crmUrl;
        $Global:CdsContext.AuthType = $ConnectionString | Out-CdsConnectionStringParameter -ParameterName "AuthType";
        if($xrmClient.OrganizationServiceProxy.ClientCredentials.UserName)
        {
            $Global:CdsContext.UserName = $xrmClient.OrganizationServiceProxy.ClientCredentials.UserName.UserName;
            $Global:CdsContext.UserPassword = $xrmClient.OrganizationServiceProxy.ClientCredentials.UserName.Password;
            $Global:CdsContext.Credentials = Set-CdsCredentials -Login $Global:CdsContext.UserName -Password $Global:CdsContext.UserPassword;
        }
        $Global:CdsContext.Region = Resolve-CdsRegionFromUrl -Url $crmUrl;
        $Global:CdsContext.AdminApiUrl = Resolve-CdsApiUrl -Region $Global:CdsContext.Region;
        $xrmClient;
    }
    end {
        $StopWatch.Stop();
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

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