A quick script for logging into Office 365 with Powershell

Connecting to Office 365 for management is pretty straightforward, but Microsoft does make changes to its service names on occasion.  If you have multiple Office 365 tenants it can also be a pain to keep them all straight.  This tiny script can be saved as a .ps1 file and modified for each account to make logging into Office 365 easy.

This uses input directly into the Powershell window for the password of the connecting account.  You can add this as a variable but I'd recommend against it since it means a password is stored in plain text.  I will cover encrypting and secure strings in another blog post.

I add Get-MSOLCompanyInformation  to make sure I am connected to the right tenant space.

This topic has been covered before of course, this blog just pulls together the most recent ConnectionURI along with snippets from Technet an other blogs.  You can see them here:

http://jeffwouters.nl/index.php/2012/12/keep-your-powershell-script-open-when-executed/

https://technet.microsoft.com/en-us/library/jj984289(v=exchg.160).aspx

https://blogs.technet.microsoft.com/mitchelatmicrosoft/2014/12/22/connecting-powershell-to-your-office-365-tenant-to-manage-exchange-and-azure-ad-simultaneously/

param ( $Show )
if ( !$Show ) 
{
    PowerShell -NoExit -File $MyInvocation.MyCommand.Path 1
    return
}
Import-Module MSOnline
$username = "ADMIN-ID@DOMAINNAME.TLD"
Write-Output " Enter Password for account " $Username
$password = read-host -assecurestring
$objcred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$password
$Office365Session = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $objcred -Authentication Basic -AllowRedirection
Import-PSSession $Office365Session
Connect-MsolService –Credential $objcred
Get-MsolCompanyInformation

Remember you need the latest prerequisite software on the system you are using to connect.  Staying on the latest version is critical as Microsoft is constantly changing their infrastructure.

Sign-In Assistant:

http://www.microsoft.com/en-us/download/details.aspx?id=39267

Windows Azure Active Directory Module for Windows PowerShell

http://go.microsoft.com/fwlink/p/?linkid=236297

Hitting a message about script execution policy?

Set-ExecutionPolicy RemoteSigned