Author Posts

July 26, 2016 at 1:12 pm

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
}

July 26, 2016 at 1:37 pm

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.

July 26, 2016 at 3:16 pm

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
}

July 26, 2016 at 4:00 pm

Someone asked me to try changing to this

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

Now it works. why does this work?