Simpele script
# Import active directory module
Import-Module ActiveDirectory
#Prompt users for CSV file path
$filepath = Read-Host -Prompt “Please enter the path to your CSV file “
#Import the file into a varaible
$users = Import-Csv $filepath -Delimiter “;”
# Loop through each row containing user details in the CSV file
foreach ($user in $users) {
#Gather the users information
$fname = $user.firstname
$lname = $user.lastname
$department = if($user.department){$user.department}else{$null}
$jobdes = $user.jobdescription
$group = $user.group
$account =$user.account
$manager = if($user.manager){$user.manager}else{$null}
$phone =if($user.phone){$user.phone}else{$null}
$cell = if($user.cell){$user.cell}else{$null}
$password =if($user.password){$user.password}else{$null}
$path = $user.ou
#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 $account}) {
#If user does exist, remove from all groups, update de user info & re-assign groups
Get-ADUser -Identity $account -Properties MemberOf | ForEach-Object {
$_.MemberOf | Remove-ADGroupMember -Members $_.DistinguishedName -Confirm:$false
}
Set-ADUser -Identity $account -Department $department -Description $jobdes -Manager $manager -OfficePhone $phone -MobilePhone $cell
Set-ADAccountPassword -Identity $account -NewPassword (ConvertTo-SecureString $password -AsPlainText -force) -Reset
foreach ($group in $group) {
Add-ADGroupMember -Identity $group -Members $account
}
#Write output for each updated user.
Write-Host “$account already existed and has been updated” -ForegroundColor Yellow
} else{
#Create new Ad users
New-ADUser `
-Name “$fname $lname” `
-GivenName $fname `
-Surname $lname `
-DisplayName “$fname $lname” `
-UserPrincipalName $account@JENAAM.LAN `
-SamAccountName $account `
-Path $path `
-AccountPassword (ConvertTo-secureString $password -AsPlainText -Force) `
-Department $department `
-Description $jobdes `
-OfficePhone $phone `
-MobilePhone $cell `
-Manager $manager `
-Enabled $true `
-ProfilePath “\\SV01\Profiles$\$account” `
-HomeDirectory “\\SV01\Home$\$account” `
-HomeDrive “H:”
#Add the new users to the correct groups
Add-ADGroupMember -Identity $group -Members $account
#Write output for each new user
Write-Host “The user account $account is created.” -ForegroundColor Cyan
}
#If the users exist in the AD but not in the CSV file , delete them
$ADUsers = Get-ADUser -filter * -SearchBase “OU=Justice Users,DC=JENAAM,DC=LAN” | Select SamAccountName
Foreach ($ADUser in $ADUsers.SamAccountName) {
if (-not ($Users.account -contains $ADUser)) {
Remove-ADUser $ADUser -Confirm:$false
Write-Host “$ADuser existed in the AD but not in the CSV file and has been deleted” -ForegroundColor Red
}
}
}
Read-Host -Prompt “Press Enter to exit”