How to make Exchange Online exported functions visible outside function

I have a scope issue that I found the answer to, but I thought I’d see if my fix is the only way to go or if there is a better/correct one.

Don Jones: I know in your Learn PowerShell Toolmaking In A Month of Lunches book, you say “Typing $global means you’re doing it wrong, wrong, wrong.”, thus I thought I’d bring this up here. :slight_smile:

I’ve got a function, inside of a module, that I’m using to create a PS session to Office 365 Exchange Online. It works great, except that none of the commands that are exported by the service (Ex: Get-Mailbox) are visible at the console/ISE level for me to be able to run. If I manually run the function code in the PowerShell console/ISE, I can see, and run, the exported commands. So, I know the problem is that the exported Exchange Online commands are only “visible” inside the scope of the function. I need them visible at the PowerShell console/ISE level so I can run them after the function has made the connect to the Exchange Online service.

Here is a very slimmed down version of my script that has the scope issue.

Function Connect-O365ExchangeOnline
{
  $Credential = Get-Credential
  $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Credential -Authentication Basic -AllowRedirection
  Import-PSSession $Session
}

Here is my fix:

Function Connect-O365ExchangeOnline
{
  $Credential = Get-Credential
  $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Credential -Authentication Basic -AllowRedirection
  $Global:ExportedCommands = Import-PSSession $Session
  Return $ExportedCommands
}

Is there a better/correct way to make this work? If not…Don Jones, please forgive me…lol :slight_smile:

Hi Kevyn,

I don’t know if there is a better way, but when you look at this module I see a lot of global variables.

Interesting. Thanks.

Yyyyyeah, so, you’re really running an edge case, where you want a function to be a “helper” and to genuinely modify the global scope you’re in. Using the $global modifier in that case is less of a sin. Personally I would probably have written that as a script, not a function, and just dot-sourced it - but you’re getting the same effect.

This isn’t using $global to pass data around; your goal is to legit modify the global scope, so you’re not really in the sin zone.

Thanks, Don. Haven’t yet gotten to the helper functions, in your book. I may take a sneak peak ahead. :wink: