Help with module do connect to Exchange On Premise

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of Ronnie Jorgensen Ronnie Jorgensen 4 months, 2 weeks ago.

  • Author
    Posts
  • #48257
    Profile photo of Ronnie Jorgensen
    Ronnie Jorgensen
    Participant

    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
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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
      Profile photo of Ronnie Jorgensen
      Ronnie Jorgensen
      Participant

      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
    Profile photo of Ronnie Jorgensen
    Ronnie Jorgensen
    Participant

    Someone asked me to try changing to this

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

    Now it works. why does this work?

You must be logged in to reply to this topic.