src/Connection/Out-XrmConnectionString.ps1

. ([System.IO.Path]::Combine($PSScriptRoot, "..", "_Internals", "CryptoManager.ps1"))
<#
    .SYNOPSIS
    Build Connection String from instance object.

    .DESCRIPTION
    Output connection string from given Microsoft Dataverse instance object.
    The URL comes from the instance. The credentials come from the connection of the instance (ParentConnection) when it has an authentication type, otherwise from the current connection ($Global:XrmContext.CurrentConnection):
    - Office365 or OAuth: OAuth connection string (sample application id and redirect URI, LoginPrompt=Auto), with the user name and password when the connection has them;
    - AD or Ifd: same authentication type, with the user name and password;
    - ClientSecret: application id (ClientId) and client secret;
    - Certificate: application id (ClientId) and certificate thumbprint;
    - no authentication type: URL only.
    The password and the client secret are encrypted for XrmToolBox when $Global:XrmContext.IsEncrypted is set. A value that needs it is quoted.

    .PARAMETER XrmInstance
    Microsoft Dataverse instance object (see New-XrmInstance, Get-XrmInstance, Get-XrmConnection).

    .OUTPUTS
    System.String. The connection string, with SkipDiscovery=true and a final ';'.

    .EXAMPLE
    Connect-XrmAdmin -TenantId $tenantId -ApplicationId $applicationId -ClientSecret $clientSecret;
    $instance = Get-XrmInstance -Name "contoso-dev";
    $connectionString = $instance | Out-XrmConnectionString;
    $xrmClient = New-XrmClient -ConnectionString $connectionString;

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

function Out-XrmConnectionString {
    [CmdletBinding()]
    [OutputType([String])]
    param
    (
        [Parameter(Mandatory = $true, ValueFromPipeline)]
        $XrmInstance
    )
    begin {  
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); 
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); 
    }    
    process {

        # Credentials of the instance's own connection when it has some, else of the current connection (M5)
        $xrmConnection = $Global:XrmContext.CurrentConnection;
        if ($XrmInstance.ParentConnection -and $XrmInstance.ParentConnection.AuthType) {
            $xrmConnection = $XrmInstance.ParentConnection;
        }
        $authType = [string]$xrmConnection.AuthType;
        $isEncrypted = ($Global:XrmContext -and $Global:XrmContext.IsEncrypted);

        # Values are quoted when they need it (M1: a password with ';' was cut)
        $parameters = [ordered]@{};
        if ($authType -in @("Office365", "OAuth")) {
            # Office365 is retired: OAuth with the same user name and password
            Set-XrmConnectionStringValueInternal -Parameters $parameters -Name "AuthType" -Value "OAuth";
            Set-XrmConnectionStringValueInternal -Parameters $parameters -Name "AppId" -Value "51f81489-12ee-4a9e-aaae-a2591f45987d";
            Set-XrmConnectionStringValueInternal -Parameters $parameters -Name "RedirectUri" -Value "app://58145B91-0C36-4500-8554-080854F2AC97";
            Set-XrmConnectionStringValueInternal -Parameters $parameters -Name "LoginPrompt" -Value "Auto";
        }
        elseif (-not [string]::IsNullOrWhiteSpace($authType)) {
            Set-XrmConnectionStringValueInternal -Parameters $parameters -Name "AuthType" -Value $authType;
        }
        Set-XrmConnectionStringValueInternal -Parameters $parameters -Name "Url" -Value $XrmInstance.Url;

        if ($authType -in @("Office365", "OAuth", "AD", "Ifd")) {
            # OAuth with a user name and a password (Connect-XrmClient -UserName -Password) kept them too (M5)
            if ($xrmConnection.UserName) {
                Set-XrmConnectionStringValueInternal -Parameters $parameters -Name "Username" -Value $xrmConnection.UserName;
            }
            if ($xrmConnection.Password) {
                $password = $(if ($isEncrypted) { Protect-XrmToolBoxPassword -Password $xrmConnection.Password } else { $xrmConnection.Password });
                Set-XrmConnectionStringValueInternal -Parameters $parameters -Name "Password" -Value $password;
            }
        }
        elseif ($authType -eq "ClientSecret") {
            Set-XrmConnectionStringValueInternal -Parameters $parameters -Name "ClientId" -Value $xrmConnection.ApplicationId;
            $clientSecret = $(if ($isEncrypted) { Protect-XrmToolBoxPassword -Password $xrmConnection.ClientSecret } else { $xrmConnection.ClientSecret });
            Set-XrmConnectionStringValueInternal -Parameters $parameters -Name "ClientSecret" -Value $clientSecret;
        }
        elseif ($authType -eq "Certificate") {
            Set-XrmConnectionStringValueInternal -Parameters $parameters -Name "ClientId" -Value $xrmConnection.ApplicationId;
            Set-XrmConnectionStringValueInternal -Parameters $parameters -Name "Thumbprint" -Value $xrmConnection.CertificateThumbprint;
        }
        Set-XrmConnectionStringValueInternal -Parameters $parameters -Name "SkipDiscovery" -Value "true";

        ConvertFrom-XrmConnectionStringMapInternal -Parameters $parameters;
    }
    end {
        $StopWatch.Stop();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }
}

Export-ModuleMember -Function Out-XrmConnectionString -Alias *;