Skip to main content

How to run Office365 powershell session with one click

If you are managing many companies through the powershell as me, it's easy to switch to other consumer by accident. So you can run your connection and in the last step enter password for different company which ends in redirection to another Office365 tenant, not that one you have needed.
Also, it's time waste to enter credentials twice everytime you need to logon to different tenant.
I propose you to keep your credentials in files encrypted and prepare separate scripts for every tenant.

I assume that you are using Active Directory module for powershell and can successfully connect to Office 365 by powershell. 
If not, please find instructions in "Office365: How to connect to from Powershell".

1.Store PS password in an encrypted form:

Read-Host -AsSecureString "Enter password" | ConvertFrom-SecureString | Out-File c:\temp\PasswordCompany1.txt

  • Copy file with password to the place you want. We will refer to it's path in the next step.
2. Prepare powershell script for connecting to MS Online.
This script connects to your Office365 tenant and to the MSolService using the same credentials provided in the first step.
  • Open notepad and paste this script (remember to choose the right path to your .txt file with password). Change youraccount@yourdomain.com to account you are using for connecting to company's powershell.
import-module msonline
$password = get-content c:\temp\PasswordCompany1.txt | convertto-securestring
$LiveCred=new-object -typename System.Management.Automation.PSCredential -argumentlist "youraccount@yourdomain.com",$password
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
Import-PSSession $Session
Connect-MsolService -Credential $livecred
  • Save file as powershell script, for example: company1_msol.ps1
  • It's good to place both files, .txt and .ps1 in the same folder
3.Prepare ActiveDirectory icon for running Powershell script

Go to desktop icon of Active Directory Module for Powershell. 
Copy it and rename.



If you have not had one, copy it from:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Go to properties of the icon and change target accordingly to your paths of the .txt and .ps1 files. In my case it will be:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoExit c:\temp\company1_msol.ps1



Now you can run your connection to your company from one icon.
Repeat that for any connection you have.