PowerShell Script to Connect to Microsoft365 Online Services

Download Script

Script


<#
.NOTES
    Company:		SECOTRON
    Title:			Connect-Office365OnlineServices.PS1
    Author:			thomas.geens@secotron.eu
    Requirements: 


    Version:		1.00
    Date:			February 13, 2019

    Windows Version:	WINDOWS 10 ENTERPRISE

    Disclaimer: 	This script is provided ‘AS IS’. No warranty is provided either expresses or implied.

    Copyright: 		Copyright © 2019 SECOTRON. All rights reserved.

.SYNOPSIS
   Connects to Office 365 Online Services.    

.DESCRIPTION
    This script connects to Office 365 Online Services, such as:
      - Microsoft Online Services
      - Exchange Online Services
      - SharePoint Online Services
      - Security and Compliance Center Services
      - Skype for Business Online Services

.PARAMETER Username
Used to build Credentials for Authentication. Only used when Credentials Parameter isn't provided.

.PARAMETER Password
Used to build Credentials for Authentication. Only used when Credentials Parameter isn't provided.

.PARAMETER SecurePassword
SecureString used to build Credentials for Authentication. Only used when Credentials Parameter isn't provided.

.PARAMETER Credentials
Used for Authentication.

.PARAMETER DomainHost
SharePoint Domain Host used to Connect to SharePoint Online. If not based on tenant name.

.PARAMETER OnlineServices
Which Online Services to connect to.

.EXAMPLE
    .\Connect-Office365OnlineServices.ps1 -Username $username -Password $password
    Connects to all Office 365 Online Services using the provided Username and Password

    .\Connect-Office365OnlineServices.ps1 -Username $username -SecurePassword $securePassword
    Connects to all Office 365 Online Services using the provided Username and Password as Secure String

    .\Connect-Office365OnlineServices.ps1 -Credentials $cred
    Connects to all Office 365 Online Services using the provided Credentials

    .\Connect-Office365OnlineServices.ps1 -Credentials $cred -SPODomainHost $sPODomainHost
    Connects to all Office 365 Online Services using the provided Credentials and specifying the SharePoint Online Domain Host

    .\Connect-Office365OnlineServices.ps1 -Credentials $cred -OnlineServices MSOnline, ExchangeOnline
    Connects to all Office 365 Online Services using the provided Credentials and specifying the Online Services to connect to

#>;
function Connect-Office365OnlineServices {

[CmdletBinding(
DefaultParameterSetName='Default'
)]
param (
# Username used to build $Credentials for Authentication
[Parameter(
ParameterSetName='Default',
HelpMessage='Username used to build $Credentials for Authentication',
Mandatory=$False
)]
[string]
$Username = [string]::Empty,

# Password used to build $Credentials for Authentication
[Parameter(
ParameterSetName='Default',
HelpMessage='Password as plaintext to build $Credentials for Authentication',
Mandatory=$False
)]
[string]
$Password = [string]::Empty,

# Secure Password used to build $Credentials for Authentication
[Parameter(
ParameterSetName='Default',
HelpMessage='Password used to build $Credentials for Authentication',
Mandatory=$False
)]
[securestring]
$SecurePassword = [securestring]::Empty,

# Credentials used for Authentication
[Parameter(
ParameterSetName='Default',
HelpMessage='Credentials used for Authentication',
Mandatory=$False,
Position=0,
ValueFromPipeline
)]
[ValidateNotNull()]
[System.Management.Automation.PSCredential]
$Credentials = [System.Management.Automation.PSCredential]::Empty,

# Optional DomainHost used to Connect to SharePoint Online
[Parameter(
ParameterSetName='Default',
HelpMessage='SharePoint Domain Host to connect to if not based on tenant name',
Mandatory=$False
)]
[string]
$SPODomainHost = [string]::Empty,

# Optional Online Services to connect to.
[Parameter(
ParameterSetName='Default',
HelpMessage='Online Services to connect to'
)]
[ValidateSet('MSOnline', 'ExchangeOnline', 'SharePointPnPPowerShellOnline', 'SecurityComplianceCenter', 'SkypeOnlineConnector')]
[string[]]
$OnlineServices = @('MSOnline', 'ExchangeOnline', 'SharePointPnPPowerShellOnline', 'SecurityComplianceCenter', 'SkypeOnlineConnector')
)

begin {
Write-Verbose "$((Get-Date).ToShortDateString()) : Started running $($MyInvocation.MyCommand)"

#----Initialise Variables
#Build credentials
if ($Credentials -ne [System.Management.Automation.PSCredential]::Empty) {
# Connect using argument $Credentials so do nothing

} elseif (($SecurePassword -ne [securestring]::Empty) -and ($Username -ne [string]::Empty)) {
# Connect using Secure Password and Username
$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username, $SecurePassword

} elseif (($Password -ne [string]::Empty) -and ($Username -ne [string]::Empty)) {
# Connect using Password and Username
$SecurePassword = ConvertTo-SecureString -String $Password -AsPlainText -Force
$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username, $SecurePassword
} else {
# ERROR: No Credentials were specified
$Credentials_Error = New-Object System.ArgumentException 'No credentials were specified, please provide the necessary arguments'
throw $Credentials_Error
}
}

process {
#----clean up opened sessions
Write-Host 'Cleaning up the current sessions on the computer...' -ForegroundColor Cyan -NoNewline
Get-PSSession -Name "ExchangeOnline" -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -InformationAction SilentlyContinue | Remove-PSSession
Get-PSSession -Name "SecurityComplianceCenter"  -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -InformationAction SilentlyContinue | Remove-PSSession | Out-Null
Get-PSSession | Where-Object {$_.Computername -like "*.online.lync.com"}  -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -InformationAction SilentlyContinue | Remove-PSSession
Write-Host 'Done' -ForegroundColor Green

#----Checking if all necessary modules exists and are loaded
$Modules = @('MSOnline', 'SharePointPnPPowerShellOnline','SkypeOnlineConnector')
# Perform checks
Write-Host 'Checking if all necessary modules exist locally...' -ForegroundColor Cyan
foreach ($Module in $Modules) {
# Only run if module is needed based on OnlineServices argument
if ($OnlineServices.Contains($Module)) {
# Start WinRM Service
if (Get-Service 'WinRM') { Start-Service 'WinRM' -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | Out-Null }

if (Get-Module -ListAvailable -Name $Module) {
Write-Host "$Module Module exists" -ForegroundColor green
Write-Host "Importing Module $Module..." -ForegroundColor Cyan -NoNewline
Import-Module $Module -DisableNameChecking
Write-Host 'Done' -ForegroundColor Green
} else {
Write-Host "$Module Module was not found!" -ForegroundColor red
Write-Host ''
Write-Host 'Do you want me to try to install this module?'
Write-Host '  (if necessary download the Skype Online Connector module manually)'
$answer = Read-Host -Prompt '[Y] Yes   [N] No    (default is 'Y'):'
If($answer -ne 'n') {
Write-Host "Installing Module $Module..." -ForegroundColor Cyan -NoNewline
Install-Module $Module -SkipPublisherCheck -Force -AllowClobber # -AcceptLicense
Write-Host 'Done' -ForegroundColor Green
Write-Host "Importing Module $Module..." -ForegroundColor Cyan -NoNewline
Import-Module $Module
Write-Host 'Done' -ForegroundColor Green
}
If($answer -eq 'n') {
Exit }
}
}
}
Write-Host ''

#----Connect to the MS Online Services
if ($OnlineServices.Contains('MSOnline')) {
Write-Host 'Connecting to MS Online Services...' -ForegroundColor Cyan -NoNewline
Connect-MsolService –Credential $Credentials
Write-Host 'Done' -ForegroundColor Green
}

#----Login to Exchange Online Remote Powershell and import the MS Exchange Module
if ($OnlineServices.Contains('ExchangeOnline')) {
Write-Host 'Connecting to Exchange Online...' -ForegroundColor Cyan -NoNewline
$ExOnSession = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Credentials -Authentication Basic -AllowRedirection -WarningAction SilentlyContinue  -Name "ExchangeOnline"
Import-PSSession $ExOnSession -WarningAction SilentlyContinue -DisableNameChecking -AllowClobber  |Out-Null
Write-Host 'Done' -ForegroundColor Green
}

#----Connect to SharePoint Online
if ($OnlineServices.Contains('SharePointPnPPowerShellOnline')) {
# Resolving SPO Domain Host
Write-Host 'Resolving SharePoint Online Site...' -ForegroundColor Cyan -NoNewline
if ($SPODomainHost -eq [string]::Empty) {
$tenantName = (Get-MsolDomain | Where-Object {$_.Name -like '*onmicrosoft.com'}).Name.Replace('.onmicrosoft.com', '')
$SPODomainHost = $tenantName
}
$Site = "https://$SPODomainHost-admin.sharepoint.com"
Write-Host $Site -ForegroundColor Green
Write-Host 'Connecting to SharePoint Online...' -ForegroundColor Cyan -NoNewline
Connect-PnPOnline -Url $site -Credentials $Credentials | out-null
Write-Host 'Done' -ForegroundColor Green
}

#----Login to the Security and Compliance Center Remote Powershell and import the Compliance center Module
if ($OnlineServices.Contains('SecurityComplianceCenter')) {
Write-Host 'Connecting to the Security and Compliance Center...' -ForegroundColor Cyan -NoNewline
$ComplianceSession = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $Credentials -Authentication Basic -AllowRedirection -WarningAction SilentlyContinue -Name "SecurityComplianceCenter"
Import-PSSession $ComplianceSession -WarningAction SilentlyContinue -DisableNameChecking -AllowClobber |Out-Null
Write-Host 'Done' -ForegroundColor Green
}

#----Connect to Skype For Business Online
if ($OnlineServices.Contains('SkypeOnlineConnector')) {
Write-Host 'Connecting to Skype for Business Online...' -ForegroundColor Cyan -NoNewline
$LyncSession = New-CsOnlineSession -Credential $Credentials
Import-PSSession $LyncSession -WarningAction SilentlyContinue -DisableNameChecking -AllowClobber | Out-Null
Write-Host 'Done' -ForegroundColor Green
}

[System.Text.StringBuilder]$Output = [System.Text.StringBuilder]::new("`nYou are now connected to ")
ForEach ($OnlineService in $OnlineServices) {
[void]$Output.Append("$OnlineService, ")
}
[void]$Output.Remove($Output.Length -2, 2)
[void]$Output.Append('.')
Write-Host $Output.ToString() -ForegroundColor Yellow
}

end {
Write-Verbose "$((Get-Date).ToShortDateString()) : Finished running $($MyInvocation.MyCommand)"
}
}