Functions/Instances/Get-CdsInstances.ps1

<#
    .SYNOPSIS
    Retrieve instances collection.
#>

function Get-CdsInstances {
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $false)]
        [ArgumentCompleter( { Get-CdsRegions })]
        [String]
        $Region = $Global:CdsContext.Region,

        [Parameter(Mandatory = $false)]
        [ArgumentCompleter( { Get-CdsAuthTypes })]
        [string]
        $AuthType = $Global:CdsContext.AuthType,
        
        [Parameter(Mandatory = $false)]
        [PsCredential]
        $Credentials = $Global:CdsContext.Credentials
    )
    begin {   
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); 
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); 
    }    
    process {
        $instances = @();

        $apiUrl = Resolve-CdsApiUrl -Region $Region;

        $instances = Get-CrmOrganizations -Credential $Credentials -DeploymentRegion $Region -OnLineType $AuthType;

        $cdsInstances = @();
        $instances | ForEach-Object {
            $cdsInstance = New-CdsInstance;
            $cdsInstance.Id = $_.OrganizationId;
            $cdsInstance.Name = $_.UrlHostName;
            $cdsInstance.UniqueName = $_.UniqueName;
            $cdsInstance.DisplayName = $_.FriendlyName;
            $cdsInstance.Url = $_.WebApplicationUrl;
            $cdsInstance.ApiUrl = $_.OrganizationWebAPIUrl;
            $cdsInstance.AdminApiUrl = $_.AdminWebApiUrl;
            $cdsInstance.TenantId = $_.TenantId;
            $cdsInstance.EnviromentId = $_.EnviromentId; 
            
            $cdsInstance.ConnectionString = $cdsInstance | Out-CdsConnectionString;
            $cdsInstances += $cdsInstance;
        }
        
        try {
            $adminInstances = Get-CrmInstances -ApiUrl $apiUrl -Credential $Credentials;

            $Global:CdsContext.IsAdmin = $true;
            $Global:CdsContext.AdminApiUrl = $apiUrl;
        }
        catch {            
            # Will fail here if user is not D365 admin
        } 
        
        $cdsInstances;
    }
    end {
        $StopWatch.Stop();
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

Export-ModuleMember -Function Get-CdsInstances -Alias *;