Link to home
Create AccountLog in
Avatar of CharlWiehahn
CharlWiehahnFlag for United Kingdom of Great Britain and Northern Ireland

asked on

New Ad User Account With Exchange 2007 Mailbox

Hi Guys,

I have a requirement to create a GUI script that makes it easier for our administration team to manage numerous new account creation requests. As most domain setups we have numerous types or users and a standard method (template) for creating each user type.

Because of this I chose AutoIT to create the GUI. The GUI is functioning correctly and the logic working out well. The problem that I have is that we have recently upgraded to exchange 2007 and as a result I need to use powershell to complete the mailbox part of the account creation.

The errors seem to relate to the AD account not being ready when powershell tries to create the mailbox, this is most likely due to the 2 scripting methods not connecting to the same domain controllers, however I am not sure how to check or change this.

I am looking for:
1. Assistance on how I can fix my current app/script.
2. Suggestions on a better way of doing this.
3. An added bonus would be a PS / WSH or AutoIT method of updating NTFS permissions on a network server that is accessed via DFS. XCacls does not seem to support DFS pathes.

Also, our network security policy does not allow me to install  any additional software.

The code and the errors are listed below.




Avatar of CharlWiehahn
CharlWiehahn
Flag of United Kingdom of Great Britain and Northern Ireland image

ASKER

Sorry, seem to have missed the vital information.
Func CreateAccount($TabNumber)
            If $TabNumber =  1 Then
                        GUICtrlSetState($Create,$GUI_DISABLE)
                        $LogTime = @HOUR &"_" &@MIN &"_" &@SEC &"_" &@MDAY &@MON &@YEAR
                        $logFile = @ScriptDir &"\Logging\" &@UserName &"_" &$LogTime &".Log"
            EndIf

            Local $ServerNumber = Random(1,8,1)
            Local $StoreNumber = Random(1,8,1)
            Local $usrPassword = RandomPassword()                                                                                   ;CHECK
            Local $usrFirstName = GUICtrlRead($UserCreate[$TabNumber][7])            ;CHECK
            Local $usrLastName = GUICtrlRead($UserCreate[$TabNumber][8])            ;CHECK
            Local $usrDisplayName = GUICtrlRead($UserCreate[$TabNumber][9])        ;CHECK
            Local $usrUserName = GUICtrlRead($UserCreate[$TabNumber][10])          ;CHECK
            Local $usrEmail = GUICtrlRead($UserCreate[$TabNumber][11])                 ;CHECK
            Local $usrEmail1 = $usrUserName &"@myotherdomain1.Local"
            Local $usrEmail2 = $usrUserName &"@myotherdomain2.local"
            Local $usrHome = GUICtrlRead($UserCreate[$TabNumber][21])                 ;CHECK
            Local $usrProfile = GUICtrlRead($UserCreate[$TabNumber][22])    ;CHECK
            Local $usrChange = GUICtrlRead($UserCreate[$TabNumber][23])              ;CHECK
            Local $usrEXM = "MAIL" &$ServerNumber                                                                               ;CHECK
            Local $usrEXMStore = $usrEXM &"\" &$usrEXM &"S" &$StoreNumber &"\" &$usrEXM &"DB" &$StoreNumber

 
            _AD_Open()
            _AD_CreateUser("OU=Users,DC=MyDomain,DC=Com", $usrUserName, $usrUserName)

            If @error Then
                _AD_Close()
                Return "Failed"
            EndIf

 
            For $TCNT = 0 to (_GUICtrlListBox_GetCount($UserCreate[$TabNumber][12]) - 1) Step 1
                _AD_AddUserToGroup(_GUICtrlListBox_GetText($UserCreate[$TabNumber][12], $TCNT), $usrUserName)	;Adds user to custom list of AD groups
            Next

            _AD_ModifyAttribute($usrUserName,"givenName",$usrFirstName)
            _AD_ModifyAttribute($usrUserName,"sn",$usrLastName)
            _AD_ModifyAttribute($usrUserName,"displayName",$usrDisplayName)
            _AD_ModifyAttribute($usrUserName,"mail",$usrEmail)
            _AD_ModifyAttribute($usrUserName,"description","Created under " &$usrChange)
            _AD_ModifyAttribute($usrUserName, "homeDrive", "H:")
            _AD_ModifyAttribute($usrUserName, "homeDirectory", $usrHome)
            _AD_ModifyAttribute($usrUserName, "profilePath", $usrProfile)
            _AD_SetPassword($usrUserName,$usrPassword,1)

            _AD_Close()

            DirCreate($usrHome)
            DirCreate($usrProfile)
			
;----------- UP TO THIS POINT EVERYTHING IS WORKING FINE. IT CREATES THE AD ACCOUNT AND POPULATES ALL THE REQUIRED INFORMATION.


            PSCMD("Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin",1000)
            pscmd('Get-User "' &$usrUserName &'" | Enable-Mailbox -Database "' &$usrEXMStore &'"',1000)
            pscmd('Add-MailboxPermission "' &$usrUserName &'" -AccessRights FullAccess -user “MyDomain\' &$usrUserName &'"',100)
            pscmd('get-mailbox -identity "' &$usrUserName &'" | Add-ADpermission -ExtendedRights "Send As" -user “MyDomain\' &$usrUserName &'"',100)
            pscmd('$mbx = get-Mailbox "' &$usrUserName &'"; $mbx.EmailAddresses += "smtp:'&$usrEmail &'"; $mbx | Set-Mailbox',100)
            pscmd('Set-Mailbox "' &$usrUserName &'" -PrimarySmtpAddress "' &$usrEmail &'" -EmailAddressPolicyEnabled $false',100)
            pscmd()

            FileWriteLine($MasterLogFile,$usrChange &"|" &@UserName &"|" &$usrUserName &"|" &$usrPassword  &"|" &$usrDisplayName &"|" &$LogTime)
 
            If $TabNumber =  $UserCreate[0][0] Then
                GUICtrlSetState($Create,$GUI_ENABLE)
                MsgBox(0,"INFORMATION","ALL ACCOUNT CREATIONS COMPLETE - PLEASE CLICK OK FOR ACCOUNT DETAILS")
            EndIf
     Return
EndFunc
;=======================================================================
Func PSCMD($Command = "EXIT",$Delay = 10)
            If $PowerShell = 0 Then
                        $PowerShell = Run("c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe",@ScriptDir,@SW_SHOW,0x2)
                        Do
                        Until(WinExists("[CLASS:ConsoleWindowClass]")) and StringInStr(ControlGetText ("[CLASS:ConsoleWindowClass]","",""),"powershell.exe")
                        Sleep(1000)
            EndIf
            ControlSend("[CLASS:ConsoleWindowClass]","", "",$Command & "{ENTER}")
            Sleep($Delay)
     Return
 EndFunc
 
 ;============================================================================================================
 ;				THE ERRORS THAT ARE BEING RECEIVED
 ;============================================================================================================
 
 PS Microsoft.PowerShell.Core\FileSystem::C:\AutoIT\AccCreation> Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin
PS Microsoft.PowerShell.Core\FileSystem::C:\AutoIT\AccCreation> Get-User "NewSAMAccountName" | Enable-Mailbox -Database "MAIL1\MAIL1S1\MAIL1DB1"

Name                      Alias                ServerName       ProhibitSendQuo
                                                                ta
----                      -----                ----------       ---------------
NewSAMAccountName                    NewSAMAccountName               MAIL1          unlimited

PS Microsoft.PowerShell.Core\FileSystem::C:\AutoIT\AccCreation> Add-MailboxPermission "NewSAMAccountName" -AccessRights FullAccess -user "MyDomain\NewSAMAccountName"
Add-MailboxPermission : NewSAMAccountName was not found. Please make sure you have typed it correctly.
At line:1 char:22 + Add-MailboxPermission  <<<< "NewSAMAccountName" -AccessRights FullAccess -user "MyDomain\NewSAMAccountName"

PS Microsoft.PowerShell.Core\FileSystem::C:\AutoIT\AccCreation> get-mailbox -identity "NewSAMAccountName" | Add-ADpermission -ExtendedRights "Send As" -user "MyDomain\NewSAMAccountName" 
Get-Mailbox : NewSAMAccountName is not a mailbox user.
At line:1 char:12+ get-mailbox  <<<< -identity "NewSAMAccountName" | Add-ADpermission -ExtendedRights "Send As" -user "MyDomain\NewSAMAccountName"

PS Microsoft.PowerShell.Core\FileSystem::C:\AutoIT\AccCreation> $mbx = get-Mailbox "NewSAMAccountName"; $mbx.EmailAddresses + "smtp:James.Test32@MyDomain.com"; $mbx | Set-Mailbox
Get-Mailbox : NewSAMAccountName is not a mailbox user.
At line:1 char:19

+ $mbx = get-Mailbox  <<<< "NewSAMAccountName"; $mbx.EmailAddresses + "smtp:James.Test32@MyDomain.com"; $mbx | Set-Mailbox
smtp:James.Test32@MyDomain.com Set-Mailbox : Cannot bind argument to parameter 'Identity' because it is null.
At line:1 char:109
+ $mbx = get-Mailbox "NewSAMAccountName"; $mbx.EmailAddresses + "smtp:James.Test32@MyDomain.com"; $mbx | Set-Mailbox <<<<

PS Microsoft.PowerShell.Core\FileSystem::C:\AutoIT\AccCreation> Set-Mailbox "NewSAMAccountName" -PrimarySmtpAddress "James.Test32@MyDomain.com" -EmailAddressPolicyEnabled $false
Set-Mailbox : NewSAMAccountName is not a mailbox user.
At line:1 char:12
+ Set-Mailbox  <<<< "NewSAMAccountName" -PrimarySmtpAddress "James.Test32@MyDomain.com" -EmailAddressPolicyEnabled $false
PS Microsoft.PowerShell.Core\FileSystem::C:\AutoIT\AccCreation>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of chrismerritt
chrismerritt

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
If you change your _AD_Open() parameters, you can specify which DC to use - this I have tested;

_AD_Open("","","DC=MyDomain,DC=Com","DesiredDC.MyDomain.Com","CN=Configuration,DC=MyDomain,DC=Com")

...and if you change your PSCMD() function as shown below, it should use that same DC. This I haven't tested;
 
Func PSCMD($Command = "EXIT",$Delay = 10)
            If $PowerShell = 0 Then
                        $PowerShell = Run("c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe",@ScriptDir,@SW_SHOW,0x2)
                        Do
                        Until(WinExists("[CLASS:ConsoleWindowClass]")) and StringInStr(ControlGetText ("[CLASS:ConsoleWindowClass]","",""),"powershell.exe")
                        Sleep(1000)
						ControlSend("[CLASS:ConsoleWindowClass]","", "","$AdminSessionADSettings.ConfigurationDomainController = 'DesiredDC.MyDomain.com' {ENTER}")
						Sleep(1000)
            EndIf
            ControlSend("[CLASS:ConsoleWindowClass]","", "",$Command & "{ENTER}")
            Sleep($Delay)
     Return
 EndFunc

Open in new window


That should force PS to use the same DC you specified for the AD functions.
Hi Chrismerritt / TheGorby,

I have tried what was mentioned above to no avail. Even though I used $AdminSessionADSettings.ConfigurationDomainController and tried $AdminSessionADSettings.preferedserver as well the error message still came back for a different DC.

Perhaps the best would be kick off a PS1 file to do the following tasks.

1. Create AD Account with 2007 mailbox in a specified OU.
2. Set a password on the account and set it to require change on first logon.
3. Add detail -> First Name, Last Name, Display Name, UPN,
4, Add home and profile pathes.
5. Add a number of security groups.
6. Update description
7. Add multiple proxy addresses and set 1 default
8. Create the home and Profile pathes and permission them to include the create user account.

If I can get my hands on the above mentioned script then I plan to create the .PS1 file using the AutoIt gui and the kickoff the PS1 script thus using powershell to do all the tasks as appose to some tasks with AutoIt and some with powershell.

Any assistance with this would be appreciated.
UPDATE ...

I have created a powershell only script but still receive a simular error. Here is my script and the output. This PS1 script was executed from the powershell command line. Please advise.

===============================================================================
Script Contents
===============================================================================
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin
C:\Progra~1\Microsoft\Exchan~1\bin\Exchange.ps1
$Password = ConvertTo-SecureString "MyPassword" -AsPlaintext -Force
New-Mailbox -Alias "NewUserName" -Database "MAIL2\MAIL2SG7\MAIL2DB7" -Name "NewUserName" -OrganizationalUnit "Users" -FirstName "John" -LastName "Doe" -DisplayName "Doe, John" -UserPrincipalName "NewUserName@MyDomain.SubDomain.Local" -Password $Password
Add-MailboxPermission -identity "NewUserName" -AccessRights "FullAccess" -user "MyDomain\NewUserName"
Get-mailbox -identity "NewUserName" | Add-ADpermission -ExtendedRights "Send As" -user "MyDomain\NewUserName"
Set-Mailbox -identity "NewUserName" -PrimarySmtpAddress "John.Doe@MySubDomain.MyDomain.com" -EmailAddressPolicyEnabled $false
Exit


===============================================================================
Execution and Error
===============================================================================

PS H:\My Documents\My Scripts\AutoIT\AccCreation\AccPS1> .\NewUserName.PS1

Security Warning
Run only scripts that you trust. While scripts from the Internet can be useful,
 this script can potentially harm your computer. Do you want to run H:\My
Documents\My Scripts\AutoIT\AccCreation\AccPS1\NewUserName.PS1?
[D] Do not run  [R] Run once  [S] Suspend  [?] Help (default is "D"): R

         Welcome to the Exchange Management Shell!

 Full list of cmdlets:          get-command
 Only Exchange cmdlets:         get-excommand
 Cmdlets for a specific role:   get-help -role *UM* or *Mailbox*
 Get general help:              help
 Get help for a cmdlet:         help <cmdlet-name> or <cmdlet-name> -?
 Show quick reference guide:    quickref
 Exchange team blog:            get-exblog
 Show full output for a cmd:    <cmd> | format-list

Tip of the day #6:

Command line 911! Do you need help? Type:

 Help <cmdlet-name>  or  <cmdlet-name> -?

You can also perform wildcard character searches and partial name matches:

 Help *UM*

And you can get more details about a cmdlet by using:

 Get-Command <cmdlet-name>


Name                      Alias                ServerName       ProhibitSendQuo
                                                                ta
----                      -----                ----------       ---------------
NewUserName                    NewUserName               MAIL2          unlimited
Add-MailboxPermission : NewUserName was not found. Please make sure you have typed i
t correctly.
At H:\My Documents\My Scripts\AutoIT\AccCreation\AccPS1\NewUserName.PS1:5 char:22
+ Add-MailboxPermission  <<<< -identity "NewUserName" -AccessRights "FullAccess" -us
er "MyDomain\NewUserName"
Add-ADPermission : MyDomain.SubDomain.Local/Users/NewUserName was not found. Plea
se make sure you have typed it correctly.
At H:\My Documents\My Scripts\AutoIT\AccCreation\AccPS1\NewUserName.PS1:6 char:50
+ Get-mailbox -identity "NewUserName" | Add-ADpermission  <<<< -ExtendedRights "Send
 As" -user "MyDomain\NewUserName"


PS H:\My Documents\My Scripts\AutoIT\AccCreation\AccPS1>

Open in new window

Avatar of chrismerritt
chrismerritt

"Most PowerShell commands against Exchange 2007 support using the -DomainController to allow you to use a particular DC for a command."
I agree with chrismerritt, if the AD session settings cmdlet isn't working then try specifying the -DomainController switch for every command. I believe the format is:

-DomainController "MyDC.MyDomain.com"
I was missing -DomainController from one of my commands before the pipe. This is working fine now. The only issue left is permissioning the home and profile, but I will start a new question for that.

Thank you for your assistance.