Monday, April 30, 2012

Creating Exchange Accounts in Powershell Remotely from a Database


So after I have a program written in VB that creates Active Directory accounts and the Exchange Email accounts for Exch2003, a new twist gets thrown in with the Exchange 2010 Upgrade.

What they don’t tell you:

  • You cannot programmatically create an Exchange account in any other language than PowerShell.
  • Exchange 2010 Server comes with both PowerShell and PowerShell for Exchange – they are two separate programs, do not share the same commands or the same remote connectivity criteria.
  • The PowerShell script must run on the Exchange box remotely but using the tools in PowerShell for Exchange – which can be a little tricky.

There is a GREAT article for getting you through the hoops of just allowing your Application Server to talk to the Exchange Server:

http://www.binarytree.com/Blog/Blog/April-2011/Provisioning-Exchange-2010-Users.aspx

However, I disagree with Rob on his last two steps. The first is how he handles the execution policy.

set-executionpolicy remotesigned

I use:

Set-executionpolicy -scope currentuser –executionpolicy bypass –force

As a programmer and data administrator, I do not want to have to sign script every time I run it or create a formally signed .ps1 file for every new hire.

The second is the actual connection (which I am setting as a variable):

$Session = Enter-PSSession -ConnectionURI (http://CAS Server Hostname/powershell) -ConfigurationName Microsoft.Exchange


Getting this far still doesn’t get you to the ballgame. You will make the connection and have no functionality with Exchange script. It’s misleading.

One very important line of code is this:
Import-PSSession $Session


Now – you can use PowerShell commands remotely to create the necessary accounts.

My code from the VB program – once you have the Active Directory account set up:

Dim testTarget1 As String
Dim PSScript2 As String
Dim FileNum As Integer

testTarget1 = Dir("c:\scripts\NewMailbox.ps1")
If Not testTarget1 = "" Then
testTarget1 = "c:\scripts\NewMailbox.ps1"
Kill testTarget1
End If

testTarget1 = "c:\scripts\NewMailbox.ps1"

FileNum = FreeFile()

PSScript2 = "$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exch2010/PowerShell/" & vbNewLine
PSScript2 = PSScript2 & "Import-PSSession $Session" & vbNewLine
PSScript2 = PSScript2 & "Enable-Mailbox -identity '" & MyName & "'" & vbNewLine
PSScript2 = PSScript2 & "Set-Mailbox -Identity '" & MyName & "' -ApplyMandatoryProperties"

'Create File on Exch
Open testTarget1 For Append As #FileNum
Print #FileNum, PSScript2
Close #FileNum

'Call Powershell and run connection
Call Shell("powershell -file ""c:\scripts\NewMailbox.ps1""", vbMaximizedFocus)