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.
Follow Me