If you are working with Office 365 and often needs to connect to Office 365 PowerShell, the below PowerShell script might come handy.

The PowerShell script uses simple error handling techniques and it’s capable of connecting to Office 365 over the Proxy.

Before you use the script, don’t forget to install the required software.

Microsoft Online Signin Assistant

Windows Azure Active Directory Module

Connect to Office 365 Using PowerShell

<#	
	.NOTES
	===========================================================================
	 Created with: 	SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.136
	 Created on:   	12/6/2016 11:05 AM
	 Created by:   	Navdeep
	 Organization: 	Alivebits Consultancy Services
	 Filename:     	ConnectToOffice365WithProxy.ps1
	===========================================================================
	.DESCRIPTION
		PowerShell script to connect to Office 365 environment using Proxy settings

#>

# Get Credentails of Office 365 Admin User
$LiveCred = Get-Credential

# Import System Proxy Settings as defined of Internet Explorer
$proxysettings = New-PSSessionOption -ProxyAccessType IEConfig

# Simple Error handling
Try
{
	Import-Module MSOnline
	Connect-MsolService -credential $LiveCred
	$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection -SessionOption $proxysettings -ErrorAction SilentlyContinue
}
Catch
{
	$error[0].Exception.Message
}

if ($session)
{
	write-host -ForegroundColor GREEN "We are importing session ..."
	Import-PSSession $Session
}
else
{
	write-host -ForegroundColor RED "Something has gone wary ..."
	$error[0].Exception.Message
}