This repository has been archived on 2025-11-07. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
powershell/user adding AD/user-add.ps1
2025-11-03 15:04:44 +01:00

84 lines
2.5 KiB
PowerShell

<#
.SYNOPSIS
Adds new Active Directory users from a CSV file.
.DESCRIPTION
Reads a CSV with user details and creates corresponding AD accounts.
.NOTES
Requires RSAT / ActiveDirectory module.
#>
Import-Module ActiveDirectory
# Path to CSV file
$csvPath = ".\users.csv"
# Import from CSV
$users = Import-Csv -Path $csvPath
$base = "DC=company,DC=local"
$ous = @(
"OU=Employees,$base",
"OU=Directie,OU=Employees,$base",
"OU=HR,OU=Employees,$base",
"OU=BeheerOntwikkeling,OU=Employees,$base",
"OU=Duitsland,OU=Employees,$base",
"OU=Benelux,OU=Employees,$base",
"OU=ZuidEuropa,OU=Employees,$base",
"OU=SalesMarketing,OU=Employees,$base",
"OU=Operations,OU=Employees,$base",
"OU=FoodBeverages,OU=Employees,$base",
"OU=Hospitality,OU=Employees,$base",
"OU=ICT,OU=Employees,$base",
"OU=Finance,OU=Employees,$base"
)
foreach ($ou in $ous) {
if (-not (Get-ADOrganizationalUnit -LDAPFilter "(distinguishedName=$ou)" -ErrorAction SilentlyContinue)) {
New-ADOrganizationalUnit -Name ($ou.Split(",")[0].Replace("OU=","")) -Path ($ou.Substring($ou.IndexOf(",")+1))
Write-Host "Created OU: $ou"
} else {
Write-Host "OU already exists: $ou"
}
}
foreach ($user in $users) {
$FirstName = $user.FirstName
$LastName = $user.LastName
$Username = $user.Username
$OU = $user.OU
$Password = (ConvertTo-SecureString $user.Password -AsPlainText -Force)
$Department = $user.Department
$Title = $user.Title
$DisplayName = "$FirstName $LastName"
$Email = "$Username@example.com"
# Check if user already exists
if (Get-ADUser -Filter {SamAccountName -eq $Username}) {
Write-Host "User $Username already exists, skipping..." -ForegroundColor Yellow
continue
}
# Create the user
try {
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName $Email `
-Name $DisplayName `
-GivenName $FirstName `
-Surname $LastName `
-DisplayName $DisplayName `
-Path $OU `
-Department $Department `
-Title $Title `
-AccountPassword $Password `
-Enabled $true `
-ChangePasswordAtLogon $true
Write-Host "Created user: $DisplayName ($Username)" -ForegroundColor Green
}
catch {
Write-Host "Failed to create user $Username: $_" -ForegroundColor Red
}
}
Write-Host "User import complete."