Function: New-LocalExchangeConnection – Ensure Your PowerShell Script is Connected to Exchange 2010
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" -ForegroundColor Yellow
}
} # end function New-LocalExchangeConnection
Calling this within your script will make ensuring that your script is running with access to Exchange cmdlets much simpler.









Follow Me