PowerShell Tips: Enabling A Remote Exchange Management Shell

Time and time again, I find myself needing to remote into the Exchange 2013 server on the infrastructure I support. To quicken this process I’ve put together the following PowerShell script to create the connection for me. While it may be far from perfect, it addresses my needs quite nicely. 

function gimme-exchange ()

{

     $arrExchangeServersURI = @("https://fqdn-of-server-one/Powershell","https://fqdn-of-server-two/Powershell")

     $success = $false

     $UserCredential = Get-Credential

     ForEach ($connectionURI in $arrExchangeServersURI)

     {

        Try

        {

             If($success -ne $true)

             {

                 $getMBXconn = new-pssession -configurationname Microsoft.Exchange -connectionuri $connectionURI -Authentication Kerberos -Credential $UserCredential

                 $null = Import-PSSession -AllowClobber $getMBXConn | Out-null

                 $success = $true

             }

        }

        catch [Exception]

        {

            $strError = $_.Exception.Message

            $strError = "Error: ${strError}"

            $success = $false

        }

    }

}

The script functionality breaks down as follows:

Line 1 - declaring the function. I have named the function gimme-exchangeso once the profile loads, I simply type that to start the function.

Lines 3 to 5 - setting a few variables. I made an array of the different Exchange servers I had rather than going through some autodiscovery process. The script opens a connection to the first one, if it fails, it trys the second one, and so on. While inefficient, I don’t add and remove a lot of Exchange servers so I can get away with it since this function is just for me. Line 4 detects if the connection was successful. Line 5 prompts and stores administrative credentials that will be used to create the connection.

Line 6 - looping through all the servers specified in Line 3 begins. In a Try/Catch block, should a connection not be successful to a previous Exchange server, a new connection is created and imported. The use of –configurationname  is required since PSSession will not be created. 

Line 12 - the Exchange server is then connected to using special parameters.

Line 13 – the session is imported. Clobbering of other existing cmdlets is enabled as well as suppression of the output of the import command.

If an error is experienced anywhere in the Try block, the Catch block is setup to echo out the error message and continue looping through servers depending on how severe the error is.

Again, this script is not perfect but suits my needs. I am open to suggestions as to how to better structure the script. Be sure to submit your suggestions in the comments below.

Microsoft_Powershell_Workplace_Join