Custom PowerShell Module – Easy Remoting for Office 365

Hi,

A while back I started on a strategy of writing script modules rather than scripts or snippets in PowerShell. This led me into an interesting scenario where I was unable to use the commands I was trying to import from a remote PowerShell connection to Office 365.

I posted on Stack Overflow and TechNet and with some assistance from TechNet I was able to edit the module to accomplish what I needed.

I originally started with the following code:


Function Connect-O365{
$o365cred = Get-Credential username@domain.onmicrosoft.com
$session365 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.outlook.com/powershell/" -Credential $o365cred -Authentication Basic -AllowRedirection
Import-PSSession $session365 -AllowClobber
}

What I found was that when I ran this function directly in my PowerShell console I was able to connect without and issues and Import-PSSession was returning the commands I expected. Dot sourcing the function from a file also yielded the same results. When I first attempted to use this exported function from a imported module no commands were returned, effectively rendering the function useless.

Kazun from TechNet noted that I could use the following command to resolve this issue.

In PowerShell sessions: Import-Module (Connect-O365)

That’s when I noticed when I was using the function Connect-O365 it was simply returning a module but that module wasn’t being imported. I then made the following modification so it was forcing the module returned by Import-PSSession to be imported into my console session.


Function Connect-O365{
$o365cred = Get-Credential username@domain.onmicrosoft.com
$session365 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.outlook.com/powershell/" -Credential $o365cred -Authentication Basic -AllowRedirection
Import-Module (Import-PSSession $session365 -AllowClobber) -Global
}

Since then my team has been happily using this shortcut to connect to our Office 365 instances via PowerShell.