Powershell create user and mailbox

shortlist
shortlist used Ask the Experts™
on
I'm relatively new to powershell and I was wondering if someone could help me create a script that automates the set up of a user. Basically i'd like to create a AD user, populate some user detail fields, create a mailbox, add the user to different security groups and distribution lists, place the user object in its correct OU and send the user a welcome email. I'd like to add multiple users at any one time so I was thinking of populating a csv file with the user specific information then importing that. Background info - 2003 AD and exchange 2007

I probably need to give loads more info, if that's the case let me know and I'll endeavour to provide it.


Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Chris DentPowerShell Developer
Top Expert 2010

Commented:

CSV files are good :)

You'll be bringing together a number of different CmdLets here, something like this.

In each case you'll find the CmdLets have extensive help, visible with:

Get-Help New-Mailbox
Get-Help New-Mailbox -Full
Get-Help New-Mailbox -Full | more
Get-Help New-Mailbox -Parameter Database
etc

Chris
# Take a default password and make it into a secure string
$Password = "Default123" | ConvertTo-SecureString -AsPlainText -Force

# Start reading the CSV file, loop through each entry
Import-Csv "YourFile.csv" | ForEach-Object {

  # First step... create the user and mailbox. Assume that the 
  # CSV file has a column called Name and Database
  # The password must be a secure string, using a generic password
  # defined at the top
  $Mailbox = New-Mailbox -Name $_.Name -Database $_.Database `
    -Password $Password -UserPrincipalName $_.Email `
    -OrganizationalUnit "OU=somewhere,DC=domain,DC=com"

  # More fields can be set with Set-Mailbox and Set-User. 
  # What would you like to set?

  # Send-MailMessage requires PowerShell version 2. Check the
  # version you are using!
  Send-MailMessage -To $Mailbox.WindowsEmailAddress -From "you@domain.com" `
    -Body "Welcome Message text" -BodyAsHtml -SmtpServer "SomeServer"

# End of loop
}

Open in new window

Author

Commented:
Hi Chris,

Thats awesome, basically i'd like to fill out the usual user info like name, office, telephone, department, address etc. but the major win would be adding the user to security groups and distribution lists based on their department. Is this possible?
Chris DentPowerShell Developer
Top Expert 2010

Commented:

But of course :)

Name, alias, first name, last name, displayname, etc are all available as parameters for New-Mailbox, that'll deal with those nicely. If you want to build Name out of Firstname and Lastname we can do that, it's no problem. The same applies to the two forms of the username (sAMAccountName and UserPrincipalName).

If we assume your input CSV has similarly named fields we can do something like this in the loop we created above:


Set-User $Mailbox.DistinguishedName -Office $_.Office -Phone $_.Telephone -Department $_.Department `
  -StreetAddress "Some Street" -PostalCode "Postcode"


If we're using the Exchange 2007 CmdLets we have a few limitations on groups: The CmdLets only work with mail-enabled groups. That doesn't mean we can't do the others, just that we have to make a bit more effort. For the mail enabled groups this is what we'd do:


Add-DistributionGroupMember "$($_.Department) Group" -Member $Mailbox.DistinguishedName


For the groups that aren't mail enabled we can do this:


([ADSI]"LDAP://CN=Group Name,OU=somewhere,DC=domain,DC=com").Add("LDAP://$($Mailbox.DistinguishedName)")


Not quite as clean, but perfectly servicable.

If you'd like a more accurate view of how I'd assemble it pop in a sample of what you'd like to have in your CSV file.

Chris
Build an E-Commerce Site with Angular 5

Learn how to build an E-Commerce site with Angular 5, a JavaScript framework used by developers to build web, desktop, and mobile applications.

Author

Commented:
Cheers Chris this is a great help, below is what i'd put in my csv file allong with the format/ naming convention of what i'd like to achieve. I may be missing some obvious fileds that people would add to improve the script so the columns are by no means set in stone:

Firs name                   Joe      
Last name                   Bloggs      
Display name             Joe Bloggs
Office                  Anycity
Telephone number             +441234987654
User logon name            bloggsj
Street                  High Street      
City                  Anycity
Zip/Postal code            A12 3BC
Country                  UK
Department                  Accounts
Company                  Acompany
Email                  joe.bloggs@domain.com
Password                  password
Profile path                  \\server.domain.com\profiles$\%username%
Home folder                  connect k: to \\server.domain.com\userdata$\%username%    
Add user to OU            domain.com/Location/Users/Joe Bloggs                            
Groups                        DL_Accounts (based on the input in the department field)
Company DL’s      Additional mail enabled groups that all users require: DL_Xyz, DL_Abc
Groups                  SG_Accounts (based on the input in the department field)
Company SG’s      Additional SG’s all users require:      SG_red, SG_blue, SG_green
Create mailbox            joe.bloggs@domain.com
Alias                  BloggsJ
Automatically update based on recipient policy:      True
Exchange Store            \\mailserver\z:\SG1-DB\MDB1.edb      

Create home folder & set permissions\\server\userdata\%username%

Author

Commented:
equally i may have colums in there that may be a total waste of time so feel free to remove them. This question is quite a biggy if you want i could create another question for this bit?

Thanks

Al

Author

Commented:
Hi Chris,

Have i over cooked it with what i'd like in my csv? Its a lot of info but it'd save so much time.

Cheers

Al
Chris DentPowerShell Developer
Top Expert 2010

Commented:

Sorry, just been a little busy for the past few days. Your CSV is fine, we can probably drop a few fields but the rest are fine :)

I'll try and get something here soon.

Chris
PowerShell Developer
Top Expert 2010
Commented:

Okay, apologies for the delay. Writing notes as I go :)

Automatically update based on recipient policy - Will this ever be false? If not, you can remove it from the file.

Display name - Better for the script to build this for you based on first name and last name?

Country - That'll have to be "United Kingdom". It's a strictly defined value. If you can do this to the value you want to use it'll be fine:

[Microsoft.Exchange.Data.Directory.CountryInfo]"United Kingdom"    # Is fine
[Microsoft.Exchange.Data.Directory.CountryInfo]"UK"                      # Is not

Exchange Store - This needs to be the logical store name, the name you see when you run Get-MailboxDatabase. The path to the file isn't so useful.

Email - This will be added based on your Email Address Policy. I'd be hesitant to make the script do it.

Home folder - It would be nice to split this so you have a "Home Drive" field as well. If the drive is always K: then we can hard-set that part and leave just the path in the Home Folder field.

Company SG’s - I guess these are not mail-enabled? Comma separated list?

We can have the script deal with the DL_Department and SG_Department group membership without you having to specify those separately.

That gets us to this snippet.

Chris
Import-Csv "YourFile.csv" | ForEach-Object {

  $DisplayName = "$($_.'First Name') $($_.'Last Name')"
  $Password = $_.Password | ConvertTo-SecureString -AsPlainText -Force
  $UserPrincipalName = "$($_.'User logon name')@yourdomain.com"

  $Mailbox = New-Mailbox -Name $DisplayName -Database $_.'Exchange Store' -Password $Password `
    -UserPrincipalName $UserPrincipalName -Alias $_.Alias -DisplayName $DisplayName `
    -FirstName $_.'First Name' -LastName $_.'Last Name' -OrganizationalUnit $_.'Add user to OU' `
    -ResetPasswordOnNextLogon $True -SamAccountName $_.'User logon name'

  Set-User $Mailbox.DistinguishedName -City $_.City -Company $_.Company -CountryOrRegion $_.Country `
    -Department $_.Department -Office $_.Office -Phone $_.'Telephone number' -PostalCode $_.'Zip/Postal code' `
    -StreetAddress $_.Street

  # Set up the Profile Path and Home Folder

  $User = [ADSI]"LDAP://$($Mailbox.DistinguishedName)"
  $User.Put("profilePath", $_.'Profile Path')
  $User.Put("homeDirectory", $_.'Home folder')
  $User.Put("homeDrive", $_.'Home drive')
  $User.SetInfo()

  # Groups

  Add-DistributionGroupMember "DL_$($_.Department)" -Member $Mailbox.DistinguishedName
}

Open in new window

Author

Commented:
Hi Chris,

This is awesome, you're right about recipient policy it wil always be true.
 
Display name - Agreed re display name and it will be first name and last name.

Country - United Kingdom will be fine

Exchange store - The store name will be in the following format 'mailboxDB1'

Agreed re the email address, let the policy sort that out

Home folder - The drive will always be the same so can be hard-set

Company SG's - Yeah these are not mail enabled. I could enter them as comma separated within the csv i'm guessing i'd include them all in one cell?

DL_department & SG_Deaprtment - That would be neat if they could get taken care of without having to specify.


# Take a default password and make it into a secure string
$Password = "Default123" | ConvertTo-SecureString -AsPlainText -Force

# Start reading the CSV file, loop through each entry
Import-Csv "YourFile.csv" | ForEach-Object {

  # Create user and mailbox. Assume that the 
  # CSV file has a column called Name and Database
  $DisplayName = "$($_.'First Name') $($_.'Last Name')"
  $Password = $_.Password | ConvertTo-SecureString -AsPlainText -Force
  $UserPrincipalName = "$($_.'User logon name')@yourdomain.com"
  
  $Mailbox = New-Mailbox -Name $DisplayName -Database $_.'Exchange Store' -Password $Password `
    -UserPrincipalName $UserPrincipalName -Alias $_.Alias -DisplayName $DisplayName `
    -FirstName $_.'First Name' -LastName $_.'Last Name' -OrganizationalUnit $_.'Add user to OU' `
    -ResetPasswordOnNextLogon $True -SamAccountName $_.'User logon name'
    
  Set-User $Mailbox.DistinguishedName -City $_.City -Company $_.Company -CountryOrRegion $_.Country `
    -Department $_.Department -Office $_.Office -Phone $_.'Telephone number' -PostalCode $_.'Zip/Postal code' `
    -StreetAddress $_.Street

# Set up the Profile Path and Home Folder

  $User = [ADSI]"LDAP://$($Mailbox.DistinguishedName)"
  $User.Put("profilePath", $_.'Profile Path')
  $User.Put("homeDirectory", $_.'Home folder')
  $User.Put("homeDrive", $_.'Home drive')
  $User.SetInfo()

  # Groups

  Add-DistributionGroupMember "DL_$($_.Department)" -Member $Mailbox.DistinguishedName

  # Send-MailMessage 
  Send-MailMessage -To $Mailbox.WindowsEmailAddress -From "you@domain.com" `
    -Body "Welcome Message text" -BodyAsHtml -SmtpServer "SomeServer"

# End of loop
}

Open in new window

Author

Commented:
Hi Chris,

In the above script have i put everything in the correct order? If so i think we're nearly there just need to hard-set the drive on the home folder, sort out the Company SG and auto complete the DL_department & SG_Deaprtment somehow.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial