We had to do automation around Office 365 mailboxes a couple of days ago and struggled to do it. We looked around and found the solution in a sea of non working articles. Let this save you time if you want to do this yourself.

Why running in Azure Automation

Instead of executing a script in Windows task scheduler that requires a virtual machine (VM), we wanted to execute our mailbox script in Azure Automation. Mainly to get rid of the dependence on a VM and to benefit of a secure way to save the credentials for the script. We thought this would just work out of the box, but there is a gotcha we encountered with the Exchange PowerShell module in Azure automation.


In almost all articles, you'll find the code similar to this one:

$credential = Get-AutomationPSCredential -Name 'O365ServiceAccount'

$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri 'https://outlook.office365.com/powershell-liveid/ -Credential $credential -Authentication Basic -AllowRedirection

Import-PSSession -Session $session -DisableNameChecking -AllowClobber -DisableNameChecking

When run, we encountered an error trying to use one of the cmdlet in the module, e.g.: Get-Mailbox, the cmdlet was not found, like if Import-PSSession didn't work loading the cmdlets in the Azure Automation session.

Get-Mailbox : The term 'Get-Mailbox' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ Get-Mailbox
+ ~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (get-mailbox2:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException   


In a good blog from undocumented-feature.com, one of the comments has the answer that solved our issue. You need to import the module like this:

Import-Module (Import-PSSession -Session $session -DisableNameChecking -AllowClobber -DisableNameChecking) -Global

After doing this, we were able to call  Get-Mailbox cmdlet successfully in Azure Automation.