Professional Documents
Culture Documents
#Load data from file.csv into $ADUsers variable. Change this to wherever your CSV
file is located.
$ADUsers = Import-csv x:\path\to\csv\file.csv
#Go through each row that has user data in the CSV we just imported
foreach ($User in $ADUsers)
{
#Read user data from each field in each row and assign to variables. CSV
headers should match: sAMAccountName,
#password, givenName, sn, pager, groups. The groups field should be split with
a ; so multiple groups can be added to a user.
#For example, a groups field for a user with 3 groups may look like this:
#CN=accounting,CN=Users,DC=example,DC=com;CN=wifi,CN=Users,DC=example,DC=com;CN=don
uts,CN=Users,DC=example,DC=com
#Also, the password field should be in plain text.
$Username = $User.sAMAccountName
$Password = $User.password
$Firstname = $User.givenName
$Lastname = $User.sn
$Pager = $User.pager
$groups = $User.groups -split ";"
#If the user group membership is empty in CSV file, we delete the user from
AD. You can remove this if you want.
if ([string]::IsNullOrWhiteSpace($groups))
{
Remove-ADUser -Identity $Username -Confirm:$false
Write-Output "$Username has no groups, removing from AD"
}
#If the user group membership field does have data, let's continue on...
else
{
#Check to see if the user already exists in AD. If they do, we are updating,
not creating a new user.
if (Get-ADUser -F {SamAccountName -eq $Username})
{
#If user does exist, remove from all groups, update password, pager, &
re-assign groups
else
{
#If the user does not exist, then go ahead and create the account with
necessary attributes. You should change example.com
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username@example.com" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Firstname $Lastname" `
-EmailAddress "$Username@example.com" `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force)
`
-PasswordNeverExpires $True
#Now that the user has been created, add them to the correct groups
foreach($group in $groups){Add-ADGroupMember $group -Members $Username}