Functions/Connection/Resolve-CdsRegionFromUrl.ps1

<#
    .SYNOPSIS
    Retrieve region name according to given url.
#>

function Resolve-CdsRegionFromUrl {
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [String]
        $Url
    )
    begin {  
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); 
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); 
    }    
    process {

        if(-not ($Url.Contains(".dynamics.com")))
        {
            throw "Url '$Url' doesn't match D365/CDS pattern!";
        }

        $regions = @{ };
        $regions["NorthAmerica"] = ".crm.";
        $regions["NorthAmerica2"] = ".crm9.";
        $regions["EMEA"] = ".crm4.";
        $regions["APAC"] = ".crm5.";
        $regions["Oceania"] = ".crm6.";
        $regions["JPN"] = ".crm7.";
        $regions["SouthAmerica"] = ".crm2.";
        $regions["IND"] = ".crm8.";
        $regions["CAN"] = ".crm3.";
        $regions["UK"] = ".crm11.";
        $regions["FRANCE"] = ".crm12.";

        foreach($regionKey in $regions.Keys)
        {
            $regionValue = $regions[$regionKey];
            if($Url.Contains( $regionValue))
            {
                return $regionKey;
            }
        }

        throw "Unkown region!";
    }
    end {
        $StopWatch.Stop();
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }
}

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