Alan's sysadmin Blog

Working smarter not harder

Posts Tagged ‘Connect to Office 365’

Automating PowerShell Connection to Office 365

Posted by Alan McBurney on August 18, 2014

Connecting to Office 365 manually can be a bit of a chore especially if you need to do it on a regular basis, so why not automate the task.

Be sure the following components have been installed on your system before attempting this.

    • Azure Active Directory Module for Windows PowerShell
    • Microsoft Online Services Sign-In Assistant

In order to automate the task, credentials are exported to an XML file.

Get-Credential user@domain.com | Export-Clixml $env:USERPROFILE\Documents\MyO365Creds.xml

The cool thing about exporting the credentials used to connect to 365 using the Export-Clixml command is that the credentials are automatically encrypted within the file using DPAPI and can only by decrypted by the person who originally saved it.

image 

The final piece of the automation process is adding this into your PowerShell profile
First test to see if a profile exists

Test-Path $Profile

Running the above command will return either a True or False value.
True being that the profile exists, false that it doesn’t

If the return value is false then in order to create the profile run the code below

New-Item -Type File -Path $Profile

image

Once the profile exists, to open the Profile type

Notepad $Profile

Finally enter the following into your PowerShell profile. This will run every time you launch PowerShell

Import-Module MSOnline
$Cred = Import-Clixml $env:USERPROFILE\Documents\MyO365Creds.xml
Connect-MsolService -Credential $Cred

If you work with multiple office 365 accounts each one of these credentials can be represented by a variable within your PowerShell profile.

$Cust1Cred = Import-Clixml $env:USERPROFILE\Documents\Cust1O365Creds.xml
$Cust2Cred = Import-Clixml $env:USERPROFILE\Documents\Cust2O365Creds.xml
$Cust3Cred = Import-Clixml $env:USERPROFILE\Documents\Cust3O365Creds.xml

Typically I will omit the final line from the Profile to connect to the service.
Then its really simple to connect to a customers tenancy using

Connect-MSOLService –Credential $Cust1Cred

Posted in Office 365, PowerShell | Tagged: , , | Leave a Comment »