blog
Office 365 – Using Import-PSSession from separate module
I was building some helper code to connect to Office 365 and everything worked fine until I moved the connection logic into a separate module. The connection function itself succeeded, but the imported remote commands did not show up outside that module. No Get-Mailbox, no Get-MailContact, nothing useful where I actually wanted to use them.
The underlying issue was scope: importing a remote session from inside a module does not automatically make those commands available everywhere you expect.
Workaround one
Use Import-PSSession in your main module and keep all other code in your “connectivity” module.
Import-PSSession -Session $Session -AllowClobber -DisableNameChecking -Prefix $Prefix -Verbose:$false
And this basically works as expected. The only thing is you can't have Connect-WinExchange as a standalone command. You need to use it just to build connection.
$Session = Connect-WinExchange -Credentials $Credentials
Import-PSSession -Session $Session -AllowClobber -DisableNameChecking -Prefix $Prefix -Verbose:$false
If you can live with it.. it's good solution.
Workaround two
Other workaround is to use Import-Module. While it doesn't come as solution at first sight you can actually do something like this
Import-Module (Import-PSSession -Session $Session -AllowClobber -DisableNameChecking -Verbose:$false) -Global
Therefore your function would look like this (more or less)
function Connect-WinExchange {
[CmdletBinding()]
param(
[string] $SessionName = 'Exchange',
)
# Your Code Goes Here
Import-Module (Import-PSSession -Session $Session -AllowClobber -DisableNameChecking -Verbose:$false) -Global
}

Current note
This post describes a real scoping issue, but the broader Office 365 connection story has changed a lot since 2018. For Exchange Online, the modern path is usually the ExchangeOnlineManagement module with Connect-ExchangeOnline, not handcrafted remote PowerShell import logic.
So the lasting value in this post is less about "how to connect to Office 365" and more about this PowerShell behavior:
- commands imported inside a module may stay scoped there
- importing them into the global session changes that behavior
- if you are packaging connection logic, module scope matters