Functions/Instances/Resolve-CdsRegion.ps1

<#
    .SYNOPSIS
    Search for user region according to its credentials.
#>

function Resolve-CdsRegion {
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true)]
        [PsCredential]
        $Credentials
    )
    begin {  
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); 
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); 
    }    
    process {
        $credentials = Set-CdsCredentials -Login $Login -Password $Password;

        $regions = Get-CdsRegions;
        foreach ($region in $regions) {
            try {
                $instances = Get-CrmOrganizations -Credential $credentials -DeploymentRegion $region -OnLineType Office365 -ErrorAction SilentlyContinue -WarningAction SilentlyContinue;                
                if ($instances) {
                    $region;                
                    break;
                }
            }
            catch {
            }
        }
    }
    end {
        $StopWatch.Stop();
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }
}

Export-ModuleMember -Function Resolve-CdsRegion -Alias *;