Untitled
TssrNetro
plain_text
8 months ago
5.1 kB
7
Indexable
# Correction de l'encodage de la console
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
# Importer le module Active Directory
Import-Module ActiveDirectory
# Chemin LDAP du domaine
$domain = "ComputeSys.lan"
$domainPath = "DC=ComputeSys,DC=lan"
# Chemin du fichier CSV
$csvPath = "C:\Users\Administrateur\Documents\AD.csv"
# Vérification du fichier CSV
if (-not (Test-Path $csvPath)) {
Write-Host "ERREUR : Le fichier $csvPath est introuvable." -ForegroundColor Red
exit
}
# Création de l'UO principale "SIEGE"
$siegePath = "OU=SIEGE,$domainPath"
if (-not (Get-ADOrganizationalUnit -Filter "Name -eq 'SIEGE'" -SearchBase $domainPath -ErrorAction SilentlyContinue)) {
New-ADOrganizationalUnit -Name "SIEGE" -Path $domainPath
Write-Host "UO 'SIEGE' créée dans le domaine." -ForegroundColor Green
} else {
Write-Host "UO 'SIEGE' existe déjà." -ForegroundColor Yellow
}
# Liste des UOs à créer sous "SIEGE"
$requiredOUs = @("DIRECTION", "COMMERCIEUX", "COMPTABILITE", "ADMINISTRATEUR", "SUPPORT-01", "SUPPORT-02", "DL")
# Création des UOs nécessaires sous "SIEGE"
foreach ($ou in $requiredOUs) {
$targetOU = "OU=$ou,$siegePath"
if (-not (Get-ADOrganizationalUnit -Filter "Name -eq '$ou'" -SearchBase $siegePath -ErrorAction SilentlyContinue)) {
New-ADOrganizationalUnit -Name $ou -Path $siegePath
Write-Host "UO '$ou' créée sous 'SIEGE'." -ForegroundColor Green
} else {
Write-Host "UO '$ou' existe déjà." -ForegroundColor Yellow
}
}
# Mapping des groupes vers leurs UOs correspondantes
$groupToOUMap = @{
"GG-DIRECTION" = "DIRECTION"
"GG-SECRETARIAT-DIRECTION" = "DIRECTION"
"GG-AVANT-VENTES" = "COMMERCIEUX"
"GG-VENTE" = "COMMERCIEUX"
"GG-COMPTABILITE" = "COMPTABILITE"
"GG-ADMINISTRATEUR" = "ADMINISTRATEUR"
"GG-SUPPORT-01" = "SUPPORT-01"
"GG-SUPPORT-02" = "SUPPORT-02"
}
# Importer les données du fichier CSV
$usersData = Import-Csv -Path $csvPath -Delimiter ";" -Encoding UTF8
foreach ($entry in $usersData) {
try {
# Validation des données obligatoires
if ([string]::IsNullOrWhiteSpace($entry.prenom) -or [string]::IsNullOrWhiteSpace($entry.groupe)) {
Write-Host "Données manquantes pour : $($entry.prenom)" -ForegroundColor Yellow
continue
}
# Déterminer l'UO cible à partir du mapping du groupe vers l'UO
if ($groupToOUMap.ContainsKey($entry.groupe)) {
$ouName = $groupToOUMap[$entry.groupe]
} else {
Write-Host "ERREUR : Aucun mapping trouvé pour le groupe '$($entry.groupe)'." -ForegroundColor Red
continue
}
$targetOU = "OU=$ouName,$siegePath"
# Création sécurisée du groupe
$groupName = $entry.groupe
if (-not (Get-ADGroup -Filter { Name -eq $groupName } -SearchBase $targetOU -ErrorAction SilentlyContinue)) {
New-ADGroup -Name $groupName `
-SamAccountName $groupName `
-GroupCategory Security `
-GroupScope Global `
-Path $targetOU `
-Description "Groupe créé automatiquement le $(Get-Date)"
Write-Host "Groupe [$groupName] créé avec succès dans [$ouName]" -ForegroundColor Cyan
}
# Génération robuste du nom d'utilisateur
$firstName = $entry.prenom.Trim().Normalize("FormD") -replace '\p{M}', ''
$lastName = if ($entry.nom) { $entry.nom.Trim().Normalize("FormD") -replace '\p{M}', '' } else { "" }
$username = "$($firstName).$($lastName)".ToLower() -replace '[^a-z0-9.]'
# Création de l'utilisateur s'il n'existe pas déjà
if (-not (Get-ADUser -Filter { SamAccountName -eq $username } -ErrorAction SilentlyContinue)) {
$userParams = @{
GivenName = $firstName
Surname = $lastName
Name = "$firstName $lastName"
SamAccountName = $username
UserPrincipalName = "$username@$domain"
AccountPassword = ConvertTo-SecureString "P@ssw0rd123!" -AsPlainText -Force
Enabled = $true
Path = $targetOU
ChangePasswordAtLogon = $true
}
# Créer l'utilisateur et l'ajouter au groupe correspondant
$newUser = New-ADUser @userParams -PassThru
Add-ADGroupMember -Identity $_.groupe -Members $newUser
Write-Host "Utilisateur [$username] créé dans [$ouName]" -ForegroundColor Green
} else {
Write-Host "Utilisateur [$username] existe déjà." -ForegroundColor Yellow
}
}
catch {
Write-Host "ERREUR avec [$($entry.prenom)] : $_" | Out-File "$env:TEMP\AD_Errors.log" -Append
}
}
Write-Host "`nTraitement terminé avec succès !" -ForegroundColor Green
Editor is loading...
Leave a Comment