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.
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