Private/Connect-MMExchangeServer.ps1

function Connect-MMExchangeServer {

    [CmdletBinding()]
    param(
        $ServerFqdn,
        [switch]$Auto
    )

    if ($Auto) {
        # Exchange Management Shell
        # C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V15\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto -ClientApplication:ManagementShell "
            # C:\Program Files\Microsoft\Exchange Server\V15\Bin\ConnectFunctions.ps1

        try {
            Import-Module ActiveDirectory -ErrorAction SilentlyContinue

            # Get Configuration Naming Context dynamically
            $configNC = (Get-ADRootDSE).configurationNamingContext

            # Get the current domain DN & Build the full SearchBase path for the Configuration container
            #$domainDN = (Get-ADDomain).DistinguishedName
            #$searchBase = "CN=Configuration,$domainDN"

            # Query Exchange server objects
            #$ServerFqdn = Get-ADObject -Filter 'ObjectClass -eq "msExchExchangeServer"' -SearchBase $configNC -Property *
                # versionNumber : 1942128340
                # msExchCurrentServerRoles : 16423
                #$ServerFqdn | fl Name, adminDisplayName, *site*, versionNumber, *serialnumber*, *networkaddress*, *roles*
            $Server = (Get-ADObject -LDAPFilter '(&(objectClass=msExchExchangeServer)(msExchServerSite=*))' -SearchBase $configNC -Property *).Name
            $ServerFqdn = $Server | Select-Object -First 1
            # $Server | Select-Object -First 1 + $domainDN

        } catch {
            #Write-Host -ForegroundColor Red "Unable to import ActiveDirectory module. Error:$($Error[0])"
            Write-Output "Exchange Server: Unable to import ActiveDirectory module." #-ForegroundColor Gray
            #Continue
        }
    }
    if (!$ServerFqdn) {
        Write-Warning "Exchange Server: Not found"
        #Continue
        return $null

    } else {
        # Connect-ExchangeServer
        # https://learn.microsoft.com/en-us/powershell/exchange/connect-to-exchange-servers-using-remote-powershell?view=exchange-ps

        #$local_session = Get-PSSession
        #$local_session= @(Get-PSSession | Where {$_.ComputerName -eq $ServerFqdn -and $_.Availability -eq 'Available' -and $_.ConfigurationName -eq 'Microsoft.Exchange'})
        $local_session= Get-PSSession | Where-Object {$_.ComputerName -eq $ServerFqdn -and $_.Availability -eq 'Available' -and $_.ConfigurationName -eq 'Microsoft.Exchange'}
        If (!$local_session) {
            # $UserCredential = Get-Credential
            #$local_session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://<ServerFQDN>/PowerShell/ -Authentication Kerberos #-Credential $UserCredential
            $local_session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$($ServerFqdn)/PowerShell/ -Authentication Kerberos #-Credential $UserCredential
            Import-PSSession $local_session -DisableNameChecking -Prefix "EXCH" # ES?
        } else {
            # Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn
        }
        # Remove-PSSession $Session

        <#
            try {
                $cmd = $null; $cmd = get-command 'get-mailbox' -erroraction stop
            } catch {
                $invexpr = ". '$env:ExchangeInstallPath\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto -ClientApplication:ManagementShell"
                Invoke-Expression $invexpr
            }
        #>


        return $local_session
    }
}
#Connect-MMExchangeServer -Auto