Tuesday, February 14, 2012

Mass creating users and exchange mailboxes from a CSV using Powershell

During a swing migration to a new domain I had to quickly create a ton of users with their mailboxes to enable importing their PST files.

I found this script somewhere on the net but it had some bugs so I cleaned it up.
Note that the CSV as its first line needs labels for each column like:
fn,ln,dispname,alias,upn

and UPN is the users email address.


Function ReadCSV{
 Param([string]$fileName)
 $users = Import-Csv $fileName
 foreach ($user in $users){
 $ht  = @{
 'givenName'=$user.fn
 'sn'=$user.ln
 'displayName'=$user.dispname
 'alias'=$user.alias
 'samAccountName'=$user.alias
 'userPrincipalName' = $user.upn
 'database' = 'Mailbox Database'
 'organizationalUnit' = 'OU=Company,OU=Users,OU=Yoyodyne,DC=yoyodyne,DC=local'
 'name' = ($user.fn +" "+$user.ln)
 }
 Write-Output $ht
 }


}
Function CreateUser{
 Param($userInfo)
 $secureString = ConvertTo-SecureString "User!123" -AsPlainText –Force
 New-Mailbox  -Name $userInfo['name' ]`
 -Alias $userInfo['alias'] -UserPrincipalName $userInfo['userPrincipalName'] `
 -SamAccountName $userInfo['alias'] -Database $userInfo['Database']`
 -FirstName $userInfo['givenName'] -LastName $userInfo['sn'] `
 -OrganizationalUnit $userinfo['organizationalUnit']`
 -DisplayName $userInfo['DISPLAYNAME'] -Password $secureString -ResetPasswordOnNextLogon $false


}


Function CreateMailbox{
 PROCESS
 {
 CreateUser $_
 }
}


 ReadCSV users.csv | CreateMailbox