User Tools

Site Tools


powershell:o365:connectoazure

Connecting to Azure (and stay connected)

When you are developing scripts against Azure (or On-Premise Exchange, or any other Remote Powershell modules) is's annoying to establish a new connection everytime you run the script. This script (for Azure AD) can be used to avoid this.
This will only establish a session if you do not allready have one, and in the case it's disconnected because you had lunch, it will reconnect automatically.


#**************************************************************************************************
#************************************************ Office 365 (Online)******************************
#**************************************************************************************************
#**************************************************************************************************
function ConnectO365($Cred)
{
    Import-Module MsOnline -Prefix MSOnline
    try 
    {
        Connect-MSOnlineMsolService -Credential $Cred -ErrorAction STOP
        $exchangeonlineSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $Cred -Authentication "Basic" -AllowRedirection -Name "O365Online"
    }
    catch
    {
        $ErrorMessage = $_.Exception.Message
        Write-Host "Unable to connect to Exchange 365 Online"
        Write-Host $ErrorMessage
        return $false
    }
    return $exchangeonlineSession
}
 
function GetO365RemoteSession($Cred)
{
    $sessionlist = Get-PSSession
    foreach ($sesid in $sessionlist)
    {
        if ($sesid.Name -eq "O365Online")
        {
            # Check connection is available for use
            if ($sesid.Availability -eq "Available")
            {
                Write-Host "O365Exchange: (Reusing session) $($sesid.Name)"
                return $sesid
            }
            elseif ($sesid.Availability -eq "Busy")
            {
                Write-Host "O365Exchange: Connection is busy, please wait."
                return $null
            }
            elseif ($sesid.Availability -eq "None")
            {
                #Reconnect BROKEN in State...
                Write-Host "O365Exchange: Connection is broken, reconneting."
                Remove-PSSession $sesid
                return ConnectO365 $Cred
            }
            else
            {
                Write-Host "O365Exchange status unknown: $($sesid.Availability)"
                return $null
            }
        }
    }
    return ConnectO365 $Cred
}
 
function ImportO365($SessionID)
{
    $modulelist = Get-Module
    foreach ($mod in $modulelist)
    {
        if ($mod.ModuleType -eq "Script")
        {
            if ($mod.ExportedFunctions.ContainsKey("Set-OnlineMailboxRegionalConfiguration"))
            {
                Write-Host "O365 Module import: Found"
                return $true
            }
 
        }
    }
    # Not found - Now Import It
    try
    { 
         Import-PSSession -Session $SessionID -DisableNameChecking -Prefix Online
         Write-Host "O365 Module import: IMPORTED"
    }
    catch
    {
        $ErrorMessage = $_.Exception.Message
        Write-Host "ERROR: O365 module import failed"
        Write-Host $ErrorMessage
        return $false
    }
    return $true
}

To use the function you can call it like this:

    $O365Rem = GetO365RemoteSession $Cred
    if ($O365Rem -eq $null)
    {
        # Failed
        Write-Host "Could not Connect to O365 Online server"
        return $false
    }
    Write-Host "Connected to Exchange Online (O365)" -ForegroundColor Cyan
 
    if ((ImportO365 $O365Rem) -eq $false)
    {
        #Failed
        Write-Host "Could not load O365 Online modules"
        return $false
    }
 
    Write-Host "Imported Exchange Online (O365) modules." -ForegroundColor Cyan
powershell/o365/connectoazure.txt ยท Last modified: 2018/11/29 12:26 by admin