Creating AD users from a CSV file

I must be in scripting mood lately. Here we have a belated Christmas present in the form of a powershell script to create users from a csv file.

Again I have butchered somebody else’s script so if you’d like the unobliterated version head over to http://gallery.technet.microsoft.com/office/AD-and-mailbox-from-CSV-96a4713f – thanks Rahmat!

My own addition is the little waiting and checking section in the middle as I sometimes had the mailbox creation fail as it couldn’t see the user yet.

I’ve also added a section for creating home drives as for some reason when you assign the home folder location during the AD user creation it only adds the AD property but doesn’t actually create the folder.

For my purposes the CSV has the folowing headers:

LastName,FirstName,Username,Title,Password,OU,Database

But you could add more as needed and use in the script:

#############################################################################
# New-UserAD and Email + Home Folder
# Create email and AD Account for new Users in Contoso.com
#
# ============================================================================

$date = Get-Date
#Set up Log files for output
$ErrorLog = “C:\PS\Errorlog.txt”
$SuccessLog = “C:\PS\Successlog.txt”
Add-Content $SuccessLog “————————————————————————————————-”
Add-Content $SuccessLog $date
Add-Content $SuccessLog “————————————————————————————————-”
Add-Content $ErrorLog “—————————————————————————————————-”
Add-Content $ErrorLog $date
Add-Content $ErrorLog “—————————————————————————————————-”

## Create Session with Exchange 2010 change your URI address
$s=New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://EXCHANGESERVER/powershell -Authentication Kerberos

## Add AD Cmdlets
Import-Module ActiveDirectory
#Import CSV

$csv = @()
$csv = Import-Csv -Delimiter “,” -Path “C:\PS\newADuserList.csv”
#Get Domain Base
$searchbase = Get-ADDomain | ForEach { $_.DistinguishedName }

#Loop through all items in the CSV
ForEach ($user In $csv)
{

## change your OU with your own OU
$OU = $User.’OU’
$Password = $User.Password
$title= $user.’Title’
$lastname= ($user.’LastName’.Substring(0,1).toupper() + $User.’LastName’.Substring(1).tolower())
$Detailedname = $User.’FirstName’ + ” ” + $lastname
$UserFirstname = $User.’FirstName’
$SAM = $User.’Username’
$UPN= $SAM + “@YOURDOMAIN.COM”
$Displayname= $User.’Username’
$Dis= $User.’title’ + ” ” + “$Detailedname”
$group= “ADGROUPS TO INCLUDE USER IN”
$homedrive= $User.HomeDrive
$logonscript= “LOGON SCRIPT PATH”
$database= $User.’Database’

#Check if the User exists
$NameID = $user.’Username’
$User = Get-ADUser -LDAPFilter “(SamAccountName=$NameID)”
If ($User -eq $Null)

{
#Create the User if it doesn’t exist

$create = New-ADUser -Name $SAM -SamAccountName $SAM -UserPrincipalName $UPN -DisplayName $Displayname -Path $OU -GivenName $UserFirstname -Surname $lastname -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -Description $Dis -HomeDrive Z: -HomeDirectory $homedrive -ChangePasswordAtLogon $true;

do
{
#Wait for bit as sometimes the user creation takes a little while to take effect
sleep -seconds 3
$accountExists = get-ADUser -LDAPFilter “(SamAccountName=$SAM)”
Write-Host “.” -nonewline
} while ($accountExists -eq !$Null)

Write-Host “AD Account $Detailedname created!”

add-content $SuccessLog “User $SAM created Sucessfully.”

## Adding User to Group
Add-ADPrincipalGroupMembership -Identity $SAM -MemberOf $group

Write-Host ” Added to Groups Needed”

add-content $SuccessLog “AD User $SAM Added to groups Sucessfully.”
Write-Host -ForegroundColor Green $SAM

### Create Homedrive

# Assign the Drive letter and Home Drive for the user in Active Directory
$HomeDrive=’Z:’
$UserRoot=’\FILESERVER\USERSHARE\’
$HomeDirectory=$UserRoot+$SAM
SET-ADUSER $SAM –HomeDrive $HomeDrive –HomeDirectory $HomeDirectory

# Create the folder on the root of the common Users Share
NEW-ITEM –path $HomeDirectory -type directory -force
$Domain=’YOURDOMAIN’
$IdentityReference=$Domain+’\’+$SAM

# Set parameters for Access rule
$FileSystemAccessRights=[System.Security.AccessControl.FileSystemRights]”FullControl”
$InheritanceFlags=[System.Security.AccessControl.InheritanceFlags]”ContainerInherit, ObjectInherit”
$PropagationFlags=[System.Security.AccessControl.PropagationFlags]”None”
$AccessControl=[System.Security.AccessControl.AccessControlType]”Allow”

# Build Access Rule from parameters
$AccessRule=NEW-OBJECT System.Security.AccessControl.FileSystemAccessRule -argumentlist($IdentityReference,”FullControl”,”ObjectInherit, ContainerInherit”,”None”,”Allow”)

# Get current Access Rule from Home Folder for User
$HomeFolderACL=Get-ACL $HomeDirectory
$HomeFolderACL.AddAccessRule($AccessRule)
SET-ACL –path $HomeDirectory -AclObject $HomeFolderACL

## Creating Mailbox on EX2010
Enable-Mailbox -Identity $SAM -Alias $SAM -Database $database

## Set Dial in Properties
set-aduser $SAM -replace @{msnpallowdialin=$true}
## Set Dial in Properties
set-aduser $SAM -replace @{msnpallowdialin=$true}

Add-Content $SuccessLog “—————————————————————————————————-”

}
Else

{
## If user already exists unlock and enable user account and log message in error log.
Unlock-ADAccount -Identity $SAM
Enable-ADAccount -Identity $SAM
Write-Host -ForegroundColor Red “AD User $SAM already exists. Account unlocked.”
add-content $ErrorLog ” User Already exist : $Detailedname. Account unlocked”

Add-Content $ErrorLog “—————————————————————————————————-”

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s