How to Make Your PowerShell Session into an Exchange Management Shell

In my last blog post, Determining the Exchange Version Without Using Get-ExchangeServer,I showed how to read the Exchange version from the registry. Shortly after posting that, the questions began to roll in about "how to make my PowerShell session behave like the Exchange Management Shell".

Well, it's pretty easy.

In the New-ExchangeConnection function, I use "dot-sourcing" to minimize the work. When you dot-source something, it means you are basically including the contents of the file into YOUR file, at that location. So, I use the same setup that EMS uses; just changed to work on the proper version of Exchange, plus the little extra magic that usually happens behind the scenes, but doesn't because it's happening in my script instead of in the "real" EMS.

So here it is!

###
### New-ExchangeConnection
###
### Create a connection to an Exchange server, in a version
### appropriate way.
###

function New-ExchangeConnection
{
	### Load the versioning function

	. .\Get-ExchangeVersion.ps1

	$exchangeVersion = Get-ExchangeVersion
	if( $exchangeVersion )
	{
		switch ( $exchangeVersion.Version )
		{
			'2007'
				{
					### This first segment is handled by a PSConsole file in EMS itself
					Get-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin -EA 0
					if ($?)
					{
						## snap-in already loaded, do nothing
					}
					else
					{
						Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin
					}

					### This line makes the rest of the magic happen
					. 'C:\Program Files\Microsoft\Exchange Server\bin\Exchange.ps1'


					return 1
				}
			'2010'
				{
					### with the advent of remote PowerShell in E14, almost all
					### of the magic gets hidden
					$credential = $null
					$global:remoteSession = $null
					. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
					Connect-ExchangeServer -auto

					return 1
				}
			default
				{
					write-error "Unsupported version $($exchangeVersion.Version)"
					return 0
				}
		}
	}

	write-error "This is not an Exchange server"
	return 0
}
Published Friday, April 27, 2012 6:00 AM by michael
Filed under: , ,

Comments

No Comments