Home > Exchange Server > Function: New-LocalExchangeConnection – Ensure Your PowerShell Script is Connected to Exchange 2010

Function: New-LocalExchangeConnection – Ensure Your PowerShell Script is Connected to Exchange 2010

Description

When writing scripts that execute commands on an Exchange server, for Exchange 2010, it’s important to ensure that you’re running within a session connected to an Exchange server, and that all Exchange cmdlets are available. In Exchange 2007, we could load the Exchange snapins. But 2010 doesn’t use snapins. Some people would say that you can simply load the modules, but loading the modules bypasses RBAC, and is thus, not recommended. Mike Pfeiffer wrote a great article Managing Exchange 2010 with Remote PowerShell that sheds some light. It’s worth a read.

A solution around this is to run a PowerShell script that comes built into Exchange 2010. This makes available the Connect-ExchangeServer cmdlet, which will connect via remote PowerShell to Exchange. We can specify a server, or let the -auto option connect to the best server via autodiscover. New-LocalExchangeConnection is a function I wrote to connect:

function New-LocalExchangeConnection	{ 
	[cmdletBinding(SupportsShouldProcess = $true)]
	param(
	)
	Write-Verbose "Checking for Exchange Management Shell"
	$Sessions = Get-PSSession | Where-Object {$_.ConfigurationName -eq "Microsoft.Exchange"}
	if (!($Sessions)){
		if (Test-Path "$env:ExchangeInstallPath\bin\RemoteExchange.ps1"){
			Write-Verbose "Exchange Management Shell not found - Loading..."
			. "$env:ExchangeInstallPath\bin\RemoteExchange.ps1"
			Write-Verbose "Exchange Management Shell loaded"
			Write-Verbose "Connecting to Exchange server"
			Connect-ExchangeServer -auto
			if (Get-PSSession | Where-Object {$_.ConfigurationName -eq "Microsoft.Exchange"}){
				Write-Verbose "Connected to Exchange Server"
			}else{
				Write-Host "An error has occurred" -ForegroundColor red
			}
		}else{
			Write-Warning "Exchange Management Shell is not available on this computer"
		}
	}else{
		Write-Verbose "Exchange Management Shell already loaded"
	}
} # end function New-LocalExchangeConnection

Calling this within your script will make ensuring that your script is running with access to Exchange cmdlets much simpler.

Donations

I’ve never been one to really solicit donations for my work. My offerings are created because *I* need to solve a problem, and once I do, it makes sense to offer the results of my work to the public. I mean, let’s face it: I can’t be the only one with that particular issue, right? Quite often, to my surprise, I’m asked why I don’t have a “donate” button so people can donate a few bucks. I’ve never really put much thought into it. But those inquiries are coming more often now, so I’m yielding to them. If you’d like to donate, you can send a few bucks via PayPal at https://www.paypal.me/PatRichard. Money collected from that will go to the costs of my website (hosting and domain names), as well as to my home lab.

  1. December 28th, 2011 at 09:33 | #1

    You’ve been posting some good stuff, which is why I keep offering suggestions on taking things to the next level or to make slight tweaks that I think make it even better. The only suggestion I would make here is to take advantage of foreground (or background) color with Write-Host. Colorized output makes it very clear that what is on the screen are information messages and not any sort of pipelined output.

    Keep up the good work.

    • Pat Richard
      December 28th, 2011 at 09:45 | #2

      Done. Thanks for the suggestions.

  2. December 28th, 2011 at 09:52 | #3

    There’s a possible bug in the code, the ELSE clause may execute if Get-PSSession returns a collection of session objects.

    • Pat Richard
      December 28th, 2011 at 09:55 | #4

      The else branch should only execute if there is already a session with the config name of “Microsoft.Exchange”. Are you seeing otherwise?

      • December 28th, 2011 at 10:00 | #5

        When you execute Get-PSSession it may return a collection of session objects. In that case the following is not valid (Get-PSSession).ConfigurationName , the collection doesn’t have a ConfigurationName property.

      • December 28th, 2011 at 10:28 | #6

        This would be safer to use:

        $s = Get-PSSession | Where-Object {$_.ConfigurationName -eq ‘Microsoft.Exchange’}

        if($s)
        {
        Write-Host “Exchange Management Shell already loaded”
        }
        else
        {
        Write-Host “Exchange Management Shell not found – Loading…”

        }

        • Pat Richard
          January 21st, 2012 at 14:11 | #7

          Thanks. Finally got around to test the suggestion. Incorporated it into the post.

  3. Ed
    January 4th, 2012 at 16:14 | #8

    Write-Log “Checking for Exchange Management Shell” , you have not posted the write-log function 🙂

    Replaced it with write-host.

    • Pat Richard
      January 5th, 2012 at 06:37 | #9

      Thanks. Looks like I missed an instance when posting the code. I’ve updated the code in the post.

  4. June 4th, 2014 at 11:07 | #10

    Hey Pat,
    Your code is still relevant and great! 🙂

    you should remove thus the “ForegroundColor” from the write-verbose part as it throws an error..

    Write-Verbose : A parameter cannot be found that matches parameter name ‘ForegroundColor’.

    • Pat Richard
      June 4th, 2014 at 19:48 | #11

      Done. Thanks for noticing!

  1. No trackbacks yet.