PowerShell: Connecting to O365 with saved Credential

I had done several of Office 365 deployment recently, and here is the PowerShell Script that i used to connect to O365 & Exchange Online with the password saved on encrypted text file


  1. Download and install the following module

Microsoft Online Service Sign-in Assistant for IT Professionals RTW

Windows Azure Active Directory Module for Windows PowerShell (64-bit version)

  1. Use the following PowerShell Script to check whetherExecutionPolicy had been configured as RemoteSigned

if ($ExecutionPolicy -eq "Restricted") {

Set-ExecutionPolicy RemoteSigned
Write-Host -ForegroundColor Green "Change the ExecutionPolicy from "Restrictred" to "RemoteSigned""

else {

Write-Host -ForegroundColor Green "The existing ExecutionPolicy had been configured as $ExecutionPolicy"


  1.  Run the following PowerShell to convert the plain password to Encrypted password and save it to txt file

"P@ssw0rd" | ConvertTo-SecureString -AsPlainText -Force |ConvertFrom-SecureString | Out-File "C:\O365\MyO365Password.txt"

Here is the PowerShell Script that i used to connect to O365 & Exchange Online

#Connecting to O365 for XXX Customer
Import-Module msonline
$PasswordFile = "C:\O365\MyO365Password.txt" #"P@ssw0rd" | ConvertTo-SecureString -AsPlainText -Force |ConvertFrom-SecureString | Out-File "C:\O365\MyO365Password.txt"
$msolcred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $PAsswordFile | ConvertTo-SecureString)
Connect-MsolService -Credential $msolcred
$ExchangeURL ="https://outlook.office365.com/powershell-liveid/"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $ExchangeURL -Credential $msolcred -Authentication Basic –AllowRedirection
Import-PSSession $session

I can predefined all my client O365 & Exchange Online login credential by saving their username and password to different files without typing each time i want to connect.

Once i had finished some configuration, i can disconnect the session with

Remove-PSSession $session

Reference Link

  1. Connect to all Office 365 services in a single Windows PowerShell window