Skip to content

Instantly share code, notes, and snippets.

@josheinstein
Last active June 11, 2024 01:39
Show Gist options
  • Save josheinstein/7ac1a136f4a37a9548885e6d6cafe08f to your computer and use it in GitHub Desktop.
Save josheinstein/7ac1a136f4a37a9548885e6d6cafe08f to your computer and use it in GitHub Desktop.
Imports several Office 365-related modules into the session and authenticates using saved or supplied credentials.
<#
.SYNOPSIS
Imports serveral Office365-related modules into the session and authenticates using
saved or supplied credentials.
.DESCRIPTION
This script requires the following modules, which must be installed before running.
They will be imported automatically if they are installed. If they are not installed,
the script will return with an error.
- MSOnline
The following modules are optional and will be imported if they are installed, but
If they are not installed, the script will continue, but the related services will
not be available.
- CredentialManager
- Microsoft.Online.SharePoint.PowerShell
- SkypeOnlineConnector
- MicrosoftTeams
Modules can be installed by downloading their installer package, or by running the
Install-Module command to install from the online PSGallery.
Install-Module MSOnline -Scope CurrentUser
Install-Module CredentialManager -Scope CurrentUser
.EXAMPLE
PS C:\> Connect-Office365.ps1 einsteintech
Imports modules and connects to the stored credentials for the einsteintech tenant.
If there are no stored credentials for this tenant, the user will be prompted for them.
#>
[CmdletBinding()]
param(
# The name of the Office 365 tenant to connect to.
[Parameter(Position=0, Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[String]$Tenant,
# When specified, the credential manager will not be
# used to load or save credentials between runs.
# If CredentialManager is not installed, this switch
# has no effect.
[Parameter()]
[Switch]$NoSave
)
begin {
# Terminate on unhandled errors, suppress module autoload
$ErrorActionPreference = 'Stop'
$PSModuleAutoLoadingPreference = 'None'
$Dependencies = @(
[PSCustomObject]@{Name='MSOnline';Version='1.1';Required=$true}
[PSCustomObject]@{Name='CredentialManager';Version='2.0';Required=$false}
[PSCustomObject]@{Name='Microsoft.Online.SharePoint.PowerShell';Version='16.0';Required=$false}
[PSCustomObject]@{Name='SkypeOnlineConnector';Version='7.0';Required=$false}
[PSCustomObject]@{Name='MicrosoftTeams';Version='0.9.6';Required=$false}
)
# Import modules used by this script
foreach ($D in $Dependencies) {
Write-Verbose "Importing dependency: $D"
try {
Import-Module -Name $D.Name -MinimumVersion $D.Version -DisableNameChecking
}
catch {
if ($D.Required) { Write-Error "Missing required module: $($D.Name) $($D.Version)" }
else { Write-Verbose "Missing optional module: $($D.Name) $($D.Version)" }
}
}
}
process {
# Session variables used by the script
$MSOLCredentialKey = "Office365PS:$($Tenant.ToUpper())"
$MSOLCredential = $Null
# OPTIONAL - Windows Credential Manager
if (!$NoSave -and (Get-Module CredentialManager)) {
# Try to use stored credentials if they are found,
# unless the -NoSave switch was specified.
$MSOLCredential = Get-StoredCredential -Target $MSOLCredentialKey -Type Generic
}
else {
# CredentialManager is not installed, so run as if the
# user passed the NoSave switch, since we can't save
# credentials securely anyway.
$NoSave = $True
}
# If stored credentials were not loaded, prompt the user to enter them.
if (!$MSOLCredential) {
$MSOLCredential = Get-Credential -Message "Log in to Office 365"
if (!$MSOLCredential) {
return # They cancelled out of the login dialog
}
}
# REQUIRED - Connect to MSOL
Write-Host "Connecting to MSOnline ($($MSOLCredential.UserName))... " -NoNewline
try {
Connect-MsolService -Credential $MSOLCredential
Write-Host "OK" -ForegroundColor Green
# If credentials worked, we can try to save them to the Windows
# Credential Manager, if the module is available and NoSave wasn't used.
if (!$NoSave) {
New-StoredCredential -Target $MSOLCredentialKey -Type Generic -Credentials $MSOLCredential -Persist LocalMachine -Comment "Stored Credentials for Connect-Office365.ps1" | Out-Null
}
# Try to set the window title.
# This doesn't work for PS hosts that don't implement RawUI
try { $Host.UI.RawUI.WindowTitle = "Office 365 Shell: $($MSOLCredential.UserName)" }
catch {}
}
catch {
Write-Host "ERROR" -ForegroundColor Yellow
if (!$NoSave) {
# Remove cached credentials from disk so we don't try to
# use them again.
Remove-StoredCredential -Target $MSOLCredentialKey -Type Generic -ErrorAction 0 | Out-Null
}
throw
}
# OPTIONAL - Connect to Exchange Online
Write-Host "Connecting to Exchange Online... " -NoNewline
try {
$MSOLSessionArgs = @{
ConfigurationName = 'Microsoft.Exchange'
ConnectionUri = 'https://outlook.office365.com/powershell-liveid/'
Credential = $MSOLCredential
Authentication = 'Basic'
AllowRedirection = $True
}
# Ignoring warnings on these two cmdlets.
# Session always gets redirected and always contains unapproved verbs.
$Session = New-PSSession @MSOLSessionArgs -WarningAction 0
Import-PSSession $Session -DisableNameChecking -WarningAction 0 | Out-Null
Write-Host "OK" -ForegroundColor Green
}
catch {
Write-Host "ERROR" -ForegroundColor Yellow
Write-Warning $_.Exception.Message
}
# OPTIONAL - Connect to SharePoint Online
Write-Host "Connecting to SharePoint Online... " -NoNewline
if (Get-Module Microsoft.Online.SharePoint.PowerShell) {
try {
Connect-SPOService -Url "https://${Tenant}-admin.sharepoint.com" -Credential $MSOLCredential
Write-Host "OK" -ForegroundColor Green
}
catch {
Write-Host "ERROR" -ForegroundColor Yellow
Write-Warning $_.Exception.Message
}
}
else {
Write-Host "SKIPPED" -ForegroundColor Gray
}
# OPTIONAL - Connect to Skype for Business
Write-Host "Connecting to Skype for Business... " -NoNewline
if (Get-Module SkypeOnlineConnector) {
try {
$Session = New-CsOnlineSession -Credential $MSOLCredential -WarningAction 0
Import-PSSession $Session -DisableNameChecking -WarningAction 0 | Out-Null
Write-Host "OK" -ForegroundColor Green
}
catch {
Write-Host "ERROR" -ForegroundColor Yellow
Write-Warning $_.Exception.Message
}
}
else {
Write-Host "SKIPPED" -ForegroundColor Gray
}
# OPTIONAL - Connect to Microsoft Teams
Write-Host "Connecting to Microsoft Teams... " -NoNewline
if (Get-Module MicrosoftTeams) {
try {
Connect-MicrosoftTeams -Credential $MSOLCredential | Out-Null
Write-Host "OK" -ForegroundColor Green
}
catch {
Write-Host "ERROR" -ForegroundColor Yellow
Write-Warning $_.Exception.Message
}
}
else {
Write-Host "SKIPPED" -ForegroundColor Gray
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment