O365SimpleConnect.psm1

<#
    ===========================================================================
     Created by: Rhys M
     Contact: RhysM.PS@gmail.com
     PS Gallery: https://www.powershellgallery.com/profiles/RhysM/
 
     Filename: O365SimpleConnect.psm1
    -------------------------------------------------------------------------
     Module Name: O365SimpleConnect
    ===========================================================================
#>


function O365SimpleConnect
{
    Param (
        [Parameter(Position = 0, Mandatory = $True, HelpMessage = "Office 365 Admin Account")]
        $Username,
        [Parameter(Position = 1, Mandatory = $True, HelpMessage = "Password for Account")]
        $Password,
        [Parameter(ParameterSetName = "SpecificConnection", Position = 2, Mandatory = $False, HelpMessage = "Specific Service To Connect To")]
        [ValidateSet("Exchange Online", "SharePoint Online", "Office 365 Compliance")]
        [String]$SpecificConnection,
        [Parameter(Position = 3, Mandatory = $False, HelpMessage = "Office 365 Tenant ID")]
        $TenantName
    )
    
    Function ModuleCheck
    {
        Param (
            [Parameter(Position = 0, Mandatory = $True, HelpMessage = "Name of module to be installed if not available")]
            $Name
        )
        if (Get-Module -ListAvailable -Name $Name)
        {
            Write-Output "Module: $Name exists - Proceeding"
        }
        else
        {
            Write-Output "Module: $Name is not installed - installing"
            install-module $Name -force
        }
    }
    
    $Cred = New-Object PSCustomObject
    $Cred | Add-Member -type NoteProperty -name Username -Value $Username
    $Cred | Add-Member -type NoteProperty -name Password -Value $Password
    $SessionUN = $Cred.Username
    $SessionPW = $Cred.Password
    $SecurePassword = $SessionPW | ConvertTo-SecureString -AsPlainText -Force
    $Credential = New-Object Management.Automation.PSCredential $SessionUN, $SecurePassword
    
    $ExchangeConnectionUri = "https://outlook.office365.com/powershell-liveid/"
    $ComplianceConnectionUri = "https://ps.compliance.protection.outlook.com/powershell-liveid/"
    $SharepointURL = "https://$TenantName-admin.sharepoint.com"
    
    if ($SpecificConnection)
    {
        if ($SpecificConnection -eq "SharePoint Online")
        {
            write-output "Establishing Connection To: $SpecificConnection"
            if ($SpecificConnection -eq "SharePoint Online")
            {
                if ($TenantName -eq $NULL)
                {
                    Write-Warning "Please Enter Your Tenant Name -TenantName. Example: YourTenantNameHere-admin.sharepoint.com"
                }
                else
                {
                    try
                    {
                        ModuleCheck -Name Microsoft.Online.SharePoint.PowerShell
                        Connect-SPOService -Url $SharepointURL -credential $Credential
                        write-output "Connection Established: $SharepointURL"
                    }
                    catch
                    {
                        write-output ""
                        Write-Warning "Error Occured Connecting to Office 365 PS (SharePoint Online) - Please check Username, Password or Tenant Name: $SharepointURL"
                    }
                }
                
            }
        }
        elseif ($SpecificConnection -eq "Office 365 Compliance")
        {
            try
            {
                $SessionName = "Office 365 Compliance - $Username"
                $ccSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $ComplianceConnectionUri -Credential $credential -Authentication "Basic" -AllowRedirection -Name $SessionName
                Import-Module (Import-PSSession $ccSession -Prefix CC -AllowClobber) -Global
                write-output "Connection Established"
                write-output "Prefix is: CC"
            }
            catch
            {
                write-output ""
                Write-Warning "Error Occured Connecting to Office 365 PS (Office 365 Compliance) - Please check Username or Password"
            }
        }
        elseif ($SpecificConnection -eq "Exchange Online")
        {
            try
            {
                ModuleCheck -Name MSOnline
                ModuleCheck -Name AzureAD
                sleep(1)
                
                $SessionName = "Exchange Online - $Username"
                $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $ExchangeConnectionUri -Credential $Credential -Authentication Basic -AllowRedirection -Name $SessionName
                Import-Module (Import-PSSession $Session -AllowClobber) -Global
                sleep(1)
                Connect-MsolService -Credential $Credential | Out-Null
                sleep(1)
                Connect-AzureAD -Credential $Credential | Out-Null
                write-output ""
                write-Output "Connected to Office 365 PS (Exchange Online, MSOL Service and Azure AD)"
            }
            catch
            {
                write-output ""
                Write-Warning "Error Occured Connecting to Office 365 PS (Exchange Online) - Please check Username or Password"
            }
        }
    }
    else
    {
        if (-not $PSBoundParameters.ContainsKey('SpecificConnection'))
        {
            Remove-Variable SpecificConnection
        }
        try
        {
            ModuleCheck -Name MSOnline
            ModuleCheck -Name AzureAD
            sleep(1)
            
            $SessionName = "$Username - Exchange Online"
            $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $ExchangeConnectionUri -Credential $Credential -Authentication Basic -AllowRedirection -Name $SessionName
            Import-Module (Import-PSSession $Session -AllowClobber) -Global
            sleep(1)
            Connect-MsolService -Credential $Credential | Out-Null
            sleep(1)
            Connect-AzureAD -Credential $Credential | Out-Null
            write-output ""
            write-Output "Connected to Office 365 PS (Exchange Online, MSOL Service and Azure AD)"
        }
        catch
        {
            write-output ""
            Write-Warning "Error Occured Connecting to Office 365 PS - Please check Username or Password"
        }
    }
    
}

Function O365SimpleConnect-EndSessions
{
    [CmdletBinding()]
    Param ()
    
    dynamicparam
    {
        $DynamicParamCall = 'SessionName'
        $DynamicParamHelpMSG = "Session You Would Like To End"
        $DynamicParamPosition = 0
        $DynamicParamMandatory = $False
        $SessionNames = Get-PSSession | select-Object -ExpandProperty Name
        $DataArray = @()
        Foreach ($SessionContent in $SessionNames)
        {
            $DataArray += $SessionContent
        }
        $DefaultAll = "All"
        $DataArray += "$DefaultAll"
        
        $Bucket = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameterDictionary
        $AttributeList = New-Object -TypeName System.Collections.ObjectModel.Collection[System.Attribute]
        $AttribValidateSet = New-Object System.Management.Automation.ValidateSetAttribute($DataArray)
        $AttributeList.Add($AttribValidateSet)
        $AttribParameter = New-Object System.Management.Automation.ParameterAttribute
        $AttribParameter.Mandatory = $DynamicParamMandatory
        $AttribParameter.Position = $DynamicParamPosition
        $AttribParameter.HelpMessage = $DynamicParamHelpMSG
        $AttributeList.Add($AttribParameter)
        $ParameterName = $DynamicParamCall
        $Parameter = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameter($ParameterName, [String], $AttributeList)
        $Bucket.Add($ParameterName, $Parameter)
        $Bucket
    }
    end
    {
        Foreach ($key in $PSBoundParameters.Keys)
        {
            if ($MyInvocation.MyCommand.Parameters.$key.isDynamic)
            {
                Set-Variable -Name $key -Value $PSBoundParameters.$key
            }
        }
        if ($SessionName)
        {
            If (((Get-PSSession).count) -gt "$NULL")
            {
                if ($SessionName -eq "$DefaultAll")
                {
                    $AllSessions = Get-PSSession | Select-Object  ComputerName, InstanceID, Name
                    $AllSessions
                    foreach ($OpenSession in $AllSessions)
                    {
                        $InstanceID = $OpenSession.instanceID
                        write-output "Removing Session: $InstanceID"
                        $RemoveSession = Get-PSSession -InstanceID $InstanceID
                        Remove-PSSession -Session $RemoveSession
                    }
                }
                else
                {
                    write-output "Ending $SessionName"
                    Remove-PSSession -Name $SessionName
                    write-output "Session Closed"
                }
            }
            else
            {
                write-output "No Sessions Available"
            }
        }
        else
        {
            If (((Get-PSSession).count) -gt "$NULL")
            {
                $AllSessions = Get-PSSession | Select-Object  ComputerName, InstanceID, Name
                $AllSessions
                foreach ($OpenSession in $AllSessions)
                {
                    $InstanceID = $OpenSession.instanceID
                    write-output "Removing Session: $InstanceID"
                    $RemoveSession = Get-PSSession -InstanceID $InstanceID
                    Remove-PSSession -Session $RemoveSession
                }
            }
            else
            {
                write-output "No Sessions Available"
            }
            
        }
        
    }
    
}


Export-ModuleMember -Function O365SimpleConnect,
                    O365SimpleConnect-EndSessions