Untitled

 avatar
TssrNetro
plain_text
8 days ago
4.5 kB
4
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
}

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

# Mapping des groupes vers leurs UOs
$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
        }

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

        $ouName = $groupToOUMap[$entry.groupe]
        $targetOU = "OU=$ouName,$siegePath"

        # Création du groupe s'il n'existe pas
        $groupName = $entry.groupe
        if (-not (Get-ADGroup -Filter "Name -eq '$groupName'" -SearchBase $targetOU -ErrorAction SilentlyContinue)) {
            New-ADGroup -Name $groupName -Path $targetOU -GroupScope Global -GroupCategory Security
            Write-Host "Groupe [$groupName] créé dans [$ouName]" -ForegroundColor Cyan
        }

        # Génération 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 = if ([string]::IsNullOrWhiteSpace($lastName)) {
            $firstName.ToLower() -replace '[^a-z0-9]', ''
        } else {
            "$($firstName).$($lastName)".ToLower() -replace '[^a-z0-9.]', ''
        }

        # Création de l'utilisateur
        if (-not (Get-ADUser -Filter "SamAccountName -eq '$username'")) {
            $userParams = @{
                SamAccountName = $username
                GivenName = $firstName
                Surname = $lastName
                Name = "$firstName $lastName"
                UserPrincipalName = "$username@$domain"
                AccountPassword = ConvertTo-SecureString "P@ssw0rd123!" -AsPlainText -Force
                Enabled = $true
                Path = $targetOU
            }
            $newUser = New-ADUser @userParams -PassThru

            # Ajout au groupe avec vérification
            if ($newUser -and $groupName) {
                Add-ADGroupMember -Identity $groupName -Members $newUser -ErrorAction Stop
                Write-Host "Utilisateur [$username] ajouté à [$groupName]" -ForegroundColor Green
            }
        }
    }
    catch {
        Write-Host "ERREUR avec $($entry.prenom) : $_" -ForegroundColor Red
    }
}

Write-Host "`nTraitement terminé avec succès !" -ForegroundColor Green
Editor is loading...
Leave a Comment