Using predefined credentials to connect
There are times when it will be convenient to store the username and password you want to use to connect, such as when running an unattended automated script.
You can use the -Credential parameter to pass credentials into the Connect-MsolService command. This parameter takes an object of type PSCredential. This can be done easily with the Get-Credential command. However, as you've seen previously, this command requires input from the user. To create a PSCredential object without user interaction, you will need to have a username and a password stored in a SecureString object.
You can easily create a secure password as follows:
$SecurePassword = Read-Host -Prompt "Enter password" -AsSecureString
However, this example also requires user input. To create a secure password from a plain text string, you can do the following:
$PlainPassword = "P@ssw0rd"
$SecurePassword = $PlainPassword | ConvertTo-SecureString -AsPlainText
-Force
Please note that the preceding example isn't a recommended best practice for security reasons. In a real-life case, you'd want to read the password from a secured key in the registry or maybe use the Windows Credential Manager. These can both be accessed from PowerShell, but examples of how to do this are beyond the scope of this book. We encourage you to develop your skills with PowerShell further and search for examples on the internet that will greatly improve the security of your automated scripts.
With our SecureString in place, we can now create our PSCredential object:
$UserName = "username@domain.onmicrosoft.com"
$Credentials = New-Object System.Management.Automation.PSCredential `
-ArgumentList $UserName, $SecurePassword
Now that we have our credentials, let's connect to Office 365:
Connect-MsolService -Credential $Credentials
In the example that follows, you can see how this all comes together. I used Read-Host to enter my password so that it wouldn't appear on screen, but I could just as easily have used a string:
You can see that connecting to Office 365 with stored credentials isn't too much more complicated than connecting interactively. Connecting this way opens the door for automation that can run unattended, which creates a whole new world of possibilities for managing Office 365.