Help with module do connect to Exchange On Premise

Welcome Forums General PowerShell Q&A Help with module do connect to Exchange On Premise

This topic contains 3 replies, has 2 voices, and was last updated by

 
Participant
2 years, 5 months ago.

  • Author
    Posts
  • #48257

    Participant
    Points: 21
    Rank: Member

    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
    }

  • #48261

    Keymaster
    Points: 1,785
    Helping HandTeam Member
    Rank: Community Hero

    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.

    • #48287

      Participant
      Points: 21
      Rank: Member

      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
      }
  • #48298

    Participant
    Points: 21
    Rank: Member

    Someone asked me to try changing to this

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

    Now it works. why does this work?

The topic ‘Help with module do connect to Exchange On Premise’ is closed to new replies.