# connect-to-exchange-online.ps1
# How to connect to Office 365 Cloud Services using PowerShell

# Office 365 Global Admin Credential
$username="[email protected]"
$password=ConvertTo-securestring "PLAINTEXTPASSWORD" -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username,$password
# $cred = Get-Credential

function connectToOffice365{
    param($credential=(get-credential))

    #Establishes Online Services connection to Office 365 Management Layer.
    Connect-MsolService -Credential $credential
}

function connectToSharepointOnline{
    param(
        $credential=(get-credential),
        $tenantURL
        )
         
    #Imports the base MSOnline module
    if (!(Get-Module -ListAvailable -Name MSOnline)){Install-Module MSOnline -Confirm:$false -Force;}

    #Imports SharePoint Online session commands into your local Windows PowerShell session.
    Import-Module Microsoft.Online.Sharepoint.PowerShell

    #This connects you to your SharePoint Online services. Replace your domain with the name of your SharePoint Online tenant.
    Connect-SPOService -url $tenantURL -Credential $credential
}

function connectToLyncOnline{
    param($credential=(get-credential))
    
    #Imports the base MSOnline module
    if (!(Get-Module -ListAvailable -Name MSOnline)){Install-Module MSOnline -Confirm:$false -Force;}
    
    #Imports the installed Skype for Business Online services module.
    Import-Module LyncOnlineConnector

    #Create a Skype for Business Powershell session using defined credential.
    $onlineLyncSession = New-CsOnlineSession -Credential $credential

    #Imports Skype for Business session commands into your local Windows PowerShell session.
    Import-PSSession $lyncSession
}

function disconnectExchangeOnline{
    <# manually check sessions
        PS C:\Windows\system32> Get-PSSession

     Id Name            ComputerName    ComputerType    State         ConfigurationName     Availability
     -- ----            ------------    ------------    -----         -----------------     ------------
      4 WinRM4          outlook.offi... RemoteMachine   Opened        Microsoft.Exchange       Available
      5 WinRM5          outlook.offi... RemoteMachine   Opened        Microsoft.Exchange       Available
    #>
    $activeExchangeOnlineSessionIds=(Get-PSSession |?{$_.ConfigurationName -eq "Microsoft.Exchange"}).Id    
    if($activeExchangeOnlineSessionIds){
        Remove-PSSession -id $activeExchangeOnlineSessionIds;
        write-host "session ID $activeExchangeOnlineSessionIds is disconnected."
        }
}

function connectToExchangeOnline{
    param(
        $credential=(get-credential),
        $connectionURI="https://outlook.office365.com/powershell-liveid/"
        )
    #Disconnect any active sessions prior to initiating a new one
    disconnectExchangeOnline;

    if (!($activeExchangeOnlineSessionIds)){
        #Imports the base MSOnline module
        if (!(Get-Module -ListAvailable -Name MSOnline)){Install-Module MSOnline -Confirm:$false -Force;}
	
        $GLOBAL:onlineExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $connectionURI -Credential $credential -Authentication Basic -AllowRedirection
	    Import-PSSession $onlineExchangeSession -AllowClobber -DisableNameChecking
        }else{
            write-host "An active session is already available. No new connections were made."
            }
}

#### Create mailbox resport ####
function createMailboxesReport{

    connectToExchangeOnline -credential $cred

    $reportFile="C:\mailboxesReport.csv"
    $sum=0;
    $report=@()   
    $mailboxes=Get-Mailbox -ResultSize Unlimited | sort;
    foreach ($mailbox in $mailboxes) {
	    $mailboxObject = (Get-MailboxStatistics $mailbox.SamAccountName)
	    [double]$totalItems=$([void]($mailboxObject.TotalItemSize.Value -match "^(.*) MB");$matches[1]);
	    [double]$totalDeleted=$([void]($mailboxObject.TotalDeletedItemSize.Value -match "^(.*) MB");$matches[1]);
        $thisMailboxSize=[math]::Round($totalItems+$totalDeleted,2);
        $report+=New-Object PsObject -property @{
            'DisplayName'=$($mailbox.DisplayName)
            'SamAccountName'=$($mailbox.SamAccountName)
            'PrimarySmtpAddress'=$($mailbox.PrimarySmtpAddress)
            'ServerName'=$($mailbox.ServerName)
            'LastLogonTime'=$($mailboxObject.LastLogonTime)
            'Database'=$($mailbox.Database)
            'IsMailboxEnabled'=$($mailbox.IsMailboxEnabled)
            'MailboxSizeMB'=$thisMailboxSize;
            }
	    $sum+=$thisMailboxSize;
    }
    #$sumGB=$sum/1024;
    $report+=New-Object PsObject -property @{
            'DisplayName'="Total Storage For All Mailboxes"
            'SamAccountName'=''
            'PrimarySmtpAddress'=''
            'ServerName'=''
            'LastLogonTime'=''
            'Database'=''
            'IsMailboxEnabled'=''
            'MailboxSizeMB'=$sum;
            }
    $report | Export-Csv -Path $reportFile -NoTypeInformation
    "Reviewing exported contents...`n"
    Import-Csv -Path $reportFile
    disconnectExchangeOnline;
}

createMailboxesReport