The Problem
Microsoft has several online guides to connecting to the Exchange Online Shell and the Office 365 Management Shell, which are a good guide on how to manually connect to the shells for either of those options. However, as you can see from the Exchange Shell, the expected time is five minutes to walk through the guide. Surely, many of the commands are easy to learn and remember, but it is still a manual process and how many times do you really want to type all of those different commands?!
This post will walk you through a script that I made to run these commands, with the option to utilize a saved credential if you need to use this for automation.
The Solution
The script in whole can be found on gist
Breaking It Down
We start with our parameter block which uses cmdletbinding (one day I will have a post on why this is a good idea), followed by our parameter block, containing two parameters. The first parameter is $GetCred – this will be used to indicate if we want to prompt for the admin running this script to enter their password or if we should use a saved credential. I am looking into vault credentials as a potentially better way to store the password, but for now, we use an encrypted string from a “read-host | convertto-securestring” hashed against a key value stored in the key file referenced by the parameter $KeyFile. This hash along with the hex values will allow us to decrypt the password and reuse it for future runs.
Next, we determine how we are going to connect. If the -GetCred switch is used, we will ask for the user’s credentials and use those later. Otherwise, we use the key file. The key file is a series of values like “11 22 33 44” and was used to create the initial password hash stored in “ENCRYPTEDSTRING”. $username specifies the user whose password we saved. From here, we create a credential object (just as with get-credential) for later use.
Then, we have the connection to the Exchange Online Shell. This is very similar to a script I have for connecting to our on-prem environment, but connects to the URI for the office365 shell. I had problems with multiple sessions being open and causing add behavior (even with the -AllowClobber swtich on the Import-Pssession), so I added a quick check to the script. We get all of the sessions that are open in the current instance of PowerShell, first checking to see if they are sessions for the Exchange Online Shell. If there is one, and the status is open, we then check to see if it is available. If all of that is true, we do not create a new connection, but we will inform an admin if the admin used the -Verbose switch. If we have no sessions open, we will create a new session with the credential specified above
Finally, we connect to the Microsoft Online service (general O365 commands) with either the saved credential or the previously specified credential. Together, many of the common cmdlets that are used on a daily basis by Office 365 admins are loaded and ready to use.