# disableCrmOrganization.ps1

$orgname='testOrg'
$domain='kimconnect.com'
$dnsServer='10.10.10.10'
$credentials=@{
    'kimconnect\crmAdmin'='password';
    'kimconnect\devAdmin'='password';
    }
$usernamePrefix='kimconnect\crm'
$servernameSuffix='-app01'
$ipDictionary=@{
    'dev01'='1.1.1.1';
    'prod01'='2.2.2.2';
    }
function getEnvironment($url,$ipDictionary,$dnsServer='8.8.8.8'){
    $regexDomain='(http[s]:\/{2}){0,1}([\d\w\.-]+)\/{0,1}'
    $innerUrl=.{[void]($url -match $regexDomain);$matches[2]}
    #$publicIP=[System.Net.Dns]::GetHostAddresses($domain)[0].IPAddressToString
    $publicIP=(Resolve-DnsName -Name $innerUrl -Server $dnsServer -NoHostsFile)[0].IPAddress    
    $environment=$ipDictionary.keys | Where-Object {$ipDictionary["$_"] -eq $publicIP}
    if ($environment){
        write-host "Environment is: $environment";
        return $environment
        }
    else{write-warning "No environments were matched.";return $false}
}
function disableCrmOrganization($orgName,$domain,$dnsServer,$credentials,$ipDictionary,$usernamePrefix,$servernameSuffix){
    $targetUrl="https://$orgName.$domain"
    $environment=getEnvironment $targetUrl $ipDictionary $dnsServer
    $serverName=$environment+$servernameSuffix
    $DwsServerUrl="https://auth$environment.$domain/"
    $username="$usernamePrefix$environment"
    $password=$credentials[$username]
    $encryptedPassword=ConvertTo-SecureString $password -AsPlainText -Force
    $credential=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName,$encryptedPassword
    $session=if($credential){
        try{
            New-PSSession -ComputerName $serverName -Credential $credential -ea Stop
        }catch{
            New-PSSession -ComputerName $serverName -Credential $credential -SessionOption $(new-pssessionoption -IncludePortInSPN)
        }
        }else{
            try{
                New-PSSession -ComputerName $serverName -ea Stop
            }catch{
                New-PSSession -ComputerName $serverName -SessionOption $(new-pssessionoption -IncludePortInSPN)
            }
        }
    $scriptblock={
        param($orgname,$DwsServerUrl,$username,$password)
        Add-PSSnapin Microsoft.Crm.Powershell
        try{
            #Disable-CrmOrganization $orgname -EA Stop
            #$DwsServerUrl=(get-crmsetting -SettingType IfdSettings).ExternalDomain
            $encryptedPassword=ConvertTo-SecureString $password -AsPlainText -Force
            $credential=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName,$encryptedPassword
            Disable-CrmOrganization $orgname -DwsServerUrl $DwsServerUrl -credential $credential -EA Stop
            return $true
        }catch{
            write-warning $_
            return $False
        }     
    }
    if($session.State -eq 'Opened'){
        $result=invoke-command -session $session -scriptblock $scriptblock -Args $orgname,$DwsServerUrl,$username,$password
    }else{
        write-warning "$env:computername cannot connect to $serverName via WinRM..."
        $result=$False
    }
    remove-pssession $session
    return $result
}

disableCrmOrganization $orgName $domain $dnsServer $credentials $ipDictionary $usernamePrefix $servernameSuffix