Skip to content

Instantly share code, notes, and snippets.

@mnl
Created March 27, 2019 08:03
Show Gist options
  • Save mnl/cf084321d7f654b5540f04a340ecc274 to your computer and use it in GitHub Desktop.
Save mnl/cf084321d7f654b5540f04a340ecc274 to your computer and use it in GitHub Desktop.
# Import active directory module for running AD cmdlets
Import-Module activedirectory
#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv "F:\import.csv"
function Make-Neat {
param($String)
$String.ToLower() | foreach {$_ -replace "[åä]", "a"} | foreach {$_ -replace "[^a-z.]", "o"}
}
#Loop through each row containing user details in the CSV file
foreach ($User in $ADUsers)
{
#Read user data from each field in each row and assign the data to a variable as below
#firstname,lastname,fullname,phone,street,zip,location,role
$i = 1
$fname = Make-Neat $User.firstname
$lname = Make-Neat $User.lastname
$username = $fname + $lname.Substring(0,$i)
$Password = "Linux4Ever"
$Firstname = $User.firstname
$Lastname = $User.lastname
$Displayname = $User.fullname
$OU = $User.location # OU to create in
$email = "$fname.$lname@nimell.nu"
$address = $User.street
$city = $OU
$zipcode = $User.zip
$country = "Sweden"
$telephone = $User.phone
$jobtitle = $User.role
$department = $User.role
#Check to see if the user already exists in AD
while (Get-ADUser -F {SamAccountName -eq $Username})
{
#If user does exist, give a warning
Write-Warning "A user account with username $Username already exist in Active Directory."
++$i
$username = $fname + $lname.Substring(0,$i)
}
#User does not exist then proceed to create the new user account
#Account will be created in the OU provided by the $OU variable read from the CSV file
New-ADUser -SamAccountName $Username `
-UserPrincipalName $Username `
-Name $Displayname `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True `
-GivenName "$Firstname" `
-Surname "$Lastname" `
-Enabled $True `
-Path "ou=Users,ou=$OU,dc=nimell,dc=nu" `
-DisplayName "$Displayname" `
-City $city `
-StreetAddress $address `
-PostalCode $zipcode `
-OfficePhone $telephone `
-EmailAddress $email `
-Title "$jobtitle" `
-Department "$department"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment