Untitled

 avatar
TssrNetro
plain_text
4 days ago
5.9 kB
3
Indexable
# Correction de l'encodage de la console
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# Importer le module Active Directory
Import-Module ActiveDirectory

# Chemins LDAP
$domain = "ComputeSys.lan"
$domainPath = "DC=ComputeSys,DC=lan"
$siegePath = "OU=SIEGE,$domainPath"

# 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"
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" (CORRIGÉ : "COMMERCIAUX")
$requiredOUs = @("DIRECTION", "COMMERCIAUX", "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 DarkGray
    }
}

# Mapping des groupes vers leurs UOs (CORRIGÉ : "COMMERCIAUX")
$groupToOUMap = @{
    "GG-DIRECTION"             = "DIRECTION"
    "GG-SECRETARIAT-DIRECTION" = "DIRECTION"
    "GG-AVANT-VENTES"          = "COMMERCIAUX"  # Correction ici
    "GG-VENTE"                 = "COMMERCIAUX"  # Correction ici
    "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 {
        Write-Host "`nTraitement de : $($entry.prenom) $($entry.nom)" -ForegroundColor Cyan

        # 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
        }

        # Vérification du mapping groupe/UO
        if (-not $groupToOUMap.ContainsKey($entry.groupe)) {
            Write-Host "ERREUR : Groupe '$($entry.groupe)' non configuré." -ForegroundColor Red
            continue
        }

        $ouName = $groupToOUMap[$entry.groupe]
        $targetOU = "OU=$ouName,$siegePath"
        Write-Host "|-> Destination : $ouName"

        # Création du groupe s'il n'existe pas
        $groupName = $entry.groupe
        $existingGroup = Get-ADGroup -Filter "Name -eq '$groupName'" -SearchBase $targetOU -ErrorAction SilentlyContinue
        
        if (-not $existingGroup) {
            New-ADGroup -Name $groupName -Path $targetOU -GroupScope Global -GroupCategory Security
            Write-Host "|-> [+] Groupe créé : $groupName" -ForegroundColor Green
        } else {
            Write-Host "|-> [ ] Groupe existe déjà : $groupName" -ForegroundColor DarkGray
        }

        # Génération du nom d'utilisateur (gestion des noms vides)
        $firstName = $entry.prenom.Trim().Normalize("FormD") -replace '\p{M}', ''
        $lastName = if ($entry.nom) { $entry.nom.Trim().Normalize("FormD") -replace '\p{M}', '' } else { "" }
        
        if ([string]::IsNullOrWhiteSpace($lastName)) {
            $username = $firstName.ToLower() -replace '[^a-z0-9]', ''
        } else {
            $username = "$($firstName).$($lastName)".ToLower() -replace '[^a-z0-9.]', ''
        }

        # Création de l'utilisateur
        if (-not (Get-ADUser -Filter "SamAccountName -eq '$username'" -ErrorAction SilentlyContinue)) {
            $userParams = @{
                SamAccountName      = $username
                GivenName           = $firstName
                Surname             = $lastName
                Name                = if ($lastName) { "$firstName $lastName" } else { $firstName }
                UserPrincipalName   = "$username@$domain"
                AccountPassword     = ConvertTo-SecureString "P@ssw0rd123!" -AsPlainText -Force
                Enabled             = $true
                Path                = $targetOU
                ChangePasswordAtLogon = $true
            }
            $newUser = New-ADUser @userParams -PassThru
            Write-Host "|-> [+] Utilisateur créé : $username" -ForegroundColor Green
        } else {
            $newUser = Get-ADUser -Filter "SamAccountName -eq '$username'"
            Write-Host "|-> [ ] Utilisateur existe déjà : $username" -ForegroundColor DarkGray
        }

        # Ajout au groupe avec vérification
        if ($newUser -and $existingGroup) {
            try {
                Add-ADGroupMember -Identity $existingGroup -Members $newUser -ErrorAction Stop
                Write-Host "|-> [+] Utilisateur ajouté au groupe : $groupName" -ForegroundColor Green
            } catch {
                Write-Host "|-> ERREUR : Échec lors de l'ajout au groupe [$groupName] - $($_.Exception.Message)" -ForegroundColor Red
            }
        } elseif (-not $existingGroup) {
            Write-Host "|-> ERREUR : Groupe [$groupName] introuvable dans $ouName" -ForegroundColor Red
        }
    }
    catch {
        Write-Host "ERREUR GLOBALE : $($_.Exception.Message)" -ForegroundColor Red
    }
}

Write-Host "`nTraitement terminé. Vérifiez les messages ci-dessus." -ForegroundColor Cyan
Editor is loading...
Leave a Comment