Using Import-Module -Global in a PowerShell Module

Hello all! I recently solved an issue but I don’t know why the solution worked, so I am seeking some guidance. I am working on creating a PowerShell module with various Skype for Business Online functions. One of them is creating a remote PowerShell connection out to Skype for Business Online. Here is a shortened example of the code:

function Connect-SkypeOnline
{
     $credentials = Get-Credential
     $SkypeSession = New-CsOnlineSession -Credential $credentials
     Import-PSSession -Session $SkypeSession -AllowClobber
}

After importing the module with this function, I would run the command successfully and the remote PowerShell session would be created, however, the module with all the commands would not be imported. However, if I copy/pasted the function code directly into the PowerShell window, the Connect-SkypeOnline function would work as expected and the module would be there. I found the solution here with someone doing the same thing except with Exchange Online PowerShell. Here is the working code:

function Connect-SkypeOnline
{
     $credentials = Get-Credential
     $SkypeSession = New-CsOnlineSession -Credential $credentials
     Import-Module (Import-PSSession -Session $SkypeSession -AllowClobber) -Global
}

My question is why do I have to use Import-Module -Global to make the module available outside of the my custom module?

You’ll need to read up on scope in PowerShell.

Variables created inside a function exist only within that function. So, when you ran your function, everything worked - but then it all went away when the function concluded. So you DID import the module, but the session that connected it all went away, and so the imported module stopped being a thing.

The “fix” (which is a little weird for me, to be honest) is bringing it all into the global scope, albeit through a bit of an odd loophole.

Thanks, Don! Now that you say that, the scope makes sense. It was confusing though because the remote PS session it creates is still available, just the not the module. I would assume that if the module was only good for the inside the function, then the remote PS session the function creates would also only be good inside the function. That’s what made troubleshooting it a little mind boggling.

As for the solution, is there a better way to approach this? As I’ve researched more, a few people have ran across the same issue and all had the same answer for importing it into the global scope.