Help with module do connect to Exchange On Premise

Hi all,

I might be doing this all wrong but i wanted to try to create a module that i could load and then quickly running Connect-Onprem -username X -Server X to connect to my local exchange server. Now it does connect to local exchange but i think because it is in a function once the function has run it remembers no Exchange commands. Please help

function Connect-OnPrem {
[CmdLetBinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$Username,

    [Parameter(Mandatory=$True)]
    [string]$server
)

$UserCredential = Get-Credential -UserName $Username -Message "Please enter the credentials for On-Premise Exchange."
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://$Server/PowerShell" -Authentication Kerberos -Credential $UserCredential
Import-PSSession $Session

}

Yeah, it’s because when $session goes out of scope, the session itself no longer exists, and so anything imported from that session no longer exists. You’d need to create that as a $global:session, which is probably one of the few instances where that’s the right thing to do.

Hi Don,

I am sure i am doing something wrong, but the below did not work either. i used $global:Session as you can see. still i get no Exchange commands

function Connect-OnPrem {
[CmdLetBinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$Username,

[Parameter(Mandatory=$True)]
[string]$server
)

$UserCredential = Get-Credential -UserName $Username -Message "Please enter the credentials for On-Premise Exchange."
$global:Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://$Server/PowerShell" -Authentication Kerberos -Credential $UserCredential
Import-PSSession $Session
}

Someone asked me to try changing to this

Import-Module (Import-PSSession $Session -AllowClobber) -Global

Now it works. why does this work?