Import AD User to Learn PowerShell

I wrote this script for someone who did not use PowerShell on a daily basis. I knew they wanted to create active directory user accounts in bulk from a csv file, so I wrote this with a few goals in mind:

1. Fix their issue. I wanted to show how useful it is learn PowerShell by using it to fix a real problem they had. This allowed them to create the users as desired.

2. Show the steps as plainly as possible, skipping any fancy functions or modules. I tried to write it as a plain sequence of steps.

3. Make it so they can edit the script if their csv input changes, despite them having no scripting background.

I think this should be run from the powershell ISE instead of the command line. If you open it on the left in the ISE and then open ADUC on the right, you can observe the results right away. You can “see” what the script does.

#Imports users from HR csv and sets it to variable

$users = Import-Csv -Path 'c:\path\to\csv' 

#Loops through each user, creates variable for each property and creates the user

foreach ($user in $users){

#These match the column names in the csv

$SamAccountName = $user.Username
$Name = "$($user."Last Name"), $($user."First Name") $($user.Int)."
$GivenName = $user."First Name"
$Surname = $user."Last Name"
$Initials = $user.Int
$DisplayName = "$($user."Last Name"), $($user."First Name") $($user.Int)."
$UserPrincipalName = "$($user.Username)@company.org"
$Description = "$($user."Position") - $($user."Department")"
$EmployID = $user."EE #"
$OU = "ou=ou,dc=company,dc=org"


#Creates the user

$NewUser = New-ADUser -SamAccountName $SamAccountName -Name $Name -GivenName $GivenName -Surname $Surname -Initials $Initials -DisplayName $DisplayName -UserPrincipalName $UserPrincipalName -Description $Description -OtherAttributes @{'EmployeeID' = $EmployID} -AccountPassword $newpwd -CannotChangePassword $false -ChangePasswordAtLogon $true -Enabled $true -Path $OU -PassThru

#Adds new user to group one

Add-ADGroupMember -Identity 'group one' -Members $SamAccountName

#Adds new user to group two

Add-ADGroupMember -Identity 'group two' -Members $SamAccountName

}

Leave a Reply

Your email address will not be published. Required fields are marked *