skip to content

Recherche

Azure AD / Entra ID

Administration Azure AD / Entra ID avec Microsoft Graph PowerShell - utilisateurs, groupes, MFA et tâches quotidiennes !

365
Publié le
Mis à jour le

Microsoft Entra ID (anciennement Azure AD) est le service d’identité cloud de Microsoft permettant la gestion centralisée des utilisateurs, groupes et ressources dans un environnement Microsoft 365.

📦 Installation et connexion

📌 Action🧠 Commande PowerShell
🔧 Installer Microsoft GraphInstall-Module Microsoft.Graph -Force
🔧 Installer Entra (preview)Install-Module Microsoft.Graph.Entra -AllowPrerelease
🔗 Se connecter (Graph)Connect-MgGraph -Scopes "User.ReadWrite.All","Group.ReadWrite.All"
🔗 Se connecter (Entra)Connect-Entra
✅ Vérifier connexionGet-MgContext
🚪 Se déconnecterDisconnect-MgGraph

👥 Gestion des utilisateurs

📌 Action🧠 Commande Microsoft Graph
📋 Lister tous les utilisateursGet-MgUser -All
🔍 Rechercher utilisateurGet-MgUser -Filter "DisplayName eq 'Jean Dupont'"
👁️ Détails completsGet-MgUser -UserId "jdupont@domain.com" -Property *
🔍 Recherche par UPNGet-MgUser -Filter "UserPrincipalName eq 'jdupont@domain.com'"
🔍 Recherche partielleGet-MgUser -Filter "startswith(DisplayName,'Jean')"
📧 Utilisateurs avec emailGet-MgUser -Filter "Mail ne null"

Création et modification d’utilisateurs

📌 Action🧠 Commande
👤 Créer utilisateur simpleNew-MgUser -DisplayName "Jean Dupont" -UserPrincipalName "jdupont@domain.com" -MailNickname "jdupont" -AccountEnabled
🔒 Créer avec mot de passe$PasswordProfile = @{ Password = "TempPass123!" ; ForceChangePasswordNextSignIn = $true }
New-MgUser -DisplayName "Jean Dupont" -UserPrincipalName "jdupont@domain.com" -PasswordProfile $PasswordProfile
✏️ Modifier nom affichéUpdate-MgUser -UserId "jdupont@domain.com" -DisplayName "Jean Martin"
📧 Modifier emailUpdate-MgUser -UserId "jdupont@domain.com" -Mail "jean.martin@domain.com"
🏢 Modifier départementUpdate-MgUser -UserId "jdupont@domain.com" -Department "IT"
📱 Modifier téléphoneUpdate-MgUser -UserId "jdupont@domain.com" -BusinessPhones @("01.23.45.67.89")

États des comptes

📌 Action🧠 Commande
🔒 Désactiver compteUpdate-MgUser -UserId "jdupont@domain.com" -AccountEnabled:$false
✅ Activer compteUpdate-MgUser -UserId "jdupont@domain.com" -AccountEnabled:$true
🔄 Réinitialiser MDPUpdate-MgUser -UserId "jdupont@domain.com" -PasswordProfile @{ Password = "NewPass123!" ; ForceChangePasswordNextSignIn = $true }
🗑️ Supprimer utilisateurRemove-MgUser -UserId "jdupont@domain.com"
📱 Révoquer sessionsRevoke-MgUserSignInSession -UserId "jdupont@domain.com"

🔐 Gestion MFA et authentification

📌 Action🧠 Commande
📱 Voir méthodes d’authGet-MgUserAuthenticationMethod -UserId "jdupont@domain.com"
📞 Voir téléphones MFAGet-MgUserAuthenticationPhoneMethod -UserId "jdupont@domain.com"
📧 Voir emails MFAGet-MgUserAuthenticationEmailMethod -UserId "jdupont@domain.com"
🗑️ Reset toutes méthodes MFAGet-MgUserAuthenticationMethod -UserId "jdupont@domain.com" | Remove-MgUserAuthenticationMethod -UserId "jdupont@domain.com"
🔄 Forcer réenregistrement MFAReset-MgUserAuthenticationMethodRegistration -UserId "jdupont@domain.com"
📱 Ajouter téléphone MFANew-MgUserAuthenticationPhoneMethod -UserId "jdupont@domain.com" -PhoneNumber "+33123456789" -PhoneType "mobile"

👥 Gestion des groupes

📌 Action🧠 Commande
📋 Lister groupesGet-MgGroup -All
🔍 Rechercher groupeGet-MgGroup -Filter "DisplayName eq 'IT Team'"
👁️ Membres d’un groupeGet-MgGroupMember -GroupId "group-id"
🆕 Créer groupe sécuritéNew-MgGroup -DisplayName "IT Team" -SecurityEnabled -MailEnabled:$false
🆕 Créer groupe Office 365New-MgGroup -DisplayName "Marketing" -GroupTypes @("Unified") -MailEnabled -SecurityEnabled
➕ Ajouter membreNew-MgGroupMember -GroupId "group-id" -DirectoryObjectId "user-id"
➖ Retirer membreRemove-MgGroupMember -GroupId "group-id" -DirectoryObjectId "user-id"
🗑️ Supprimer groupeRemove-MgGroup -GroupId "group-id"

📄 Licences Microsoft 365

📌 Action🧠 Commande
📋 Voir licences disponiblesGet-MgSubscribedSku
👤 Licences d’un utilisateurGet-MgUserLicenseDetail -UserId "jdupont@domain.com"
➕ Assigner licenceSet-MgUserLicense -UserId "jdupont@domain.com" -AddLicenses @{SkuId = "sku-id"} -RemoveLicenses @()
➖ Retirer licenceSet-MgUserLicense -UserId "jdupont@domain.com" -AddLicenses @() -RemoveLicenses @("sku-id")
📊 Utilisateurs sans licenceGet-MgUser -Filter "assignedLicenses/$count eq 0” -ConsistencyLevel eventual -CountVariable unlicensed`

Licences courantes et leurs SKU

SKU = Stock Keeping Unit, identifiant unique de chaque licence Microsoft dans le système

📌 Licence🏷️ SKU PartNumber💰 Type📝 Description
Microsoft 365 E3SPE_E3EnterpriseLicence complète avec Office, Teams, SharePoint
Microsoft 365 E5SPE_E5EnterpriseE3 + sécurité avancée, compliance, analytics
Microsoft 365 F3SPE_F1FrontlinePour employés de terrain (pas d’Office desktop)
Copilot for M365Microsoft_365_CopilotAdd-onIA générative (nécessite E3/E5/Business Premium)
Power BI ProPOWER_BI_PROAnalyticsRapports et dashboards

Exemples pratiques

# Compter les licences E3 assignées
(Get-MgUser -Filter "assignedLicenses/any(x:x/skuId eq (Get-MgSubscribedSku | Where SkuPartNumber -eq 'SPE_E3').SkuId)" -ConsistencyLevel eventual).Count
 
# Assigner licence E5 à un utilisateur
$E5Sku = (Get-MgSubscribedSku | Where SkuPartNumber -eq 'SPE_E5').SkuId
Set-MgUserLicense -UserId "jdupont@domain.com" -AddLicenses @{SkuId = $E5Sku} -RemoveLicenses @()
 
# Lister utilisateurs avec Copilot
Get-MgUser -Filter "assignedLicenses/any(x:x/skuId eq (Get-MgSubscribedSku | Where SkuPartNumber -eq 'Microsoft_365_Copilot').SkuId)" -ConsistencyLevel eventual

📊 Scripts d’export utiles

Export utilisateurs actifs

Get-MgUser -Filter "AccountEnabled eq true" -Property DisplayName,UserPrincipalName,Department,JobTitle,CreatedDateTime | 
Export-Csv -Path "UtilisateursActifs.csv" -NoTypeInformation -Encoding UTF8

Export groupes et membres

$Groups = Get-MgGroup -All
$Results = foreach ($Group in $Groups) {
    $Members = Get-MgGroupMember -GroupId $Group.Id
    foreach ($Member in $Members) {
        [PSCustomObject]@{
            GroupName = $Group.DisplayName
            GroupId = $Group.Id
            MemberName = (Get-MgUser -UserId $Member.Id).DisplayName
            MemberUPN = (Get-MgUser -UserId $Member.Id).UserPrincipalName
        }
    }
}
$Results | Export-Csv -Path "GroupesEtMembres.csv" -NoTypeInformation -Encoding UTF8

Export utilisateurs avec licences

$Users = Get-MgUser -All -Property DisplayName,UserPrincipalName,AssignedLicenses
$Results = foreach ($User in $Users) {
    $Licenses = $User.AssignedLicenses | ForEach-Object { 
        (Get-MgSubscribedSku | Where-Object SkuId -eq $_.SkuId).SkuPartNumber 
    }
    [PSCustomObject]@{
        DisplayName = $User.DisplayName
        UserPrincipalName = $User.UserPrincipalName
        Licenses = $Licenses -join "; "
    }
}
$Results | Export-Csv -Path "UtilisateursLicences.csv" -NoTypeInformation -Encoding UTF8

Export dernières connexions

Get-MgUser -All -Property DisplayName,UserPrincipalName,SignInActivity | 
Select-Object DisplayName, UserPrincipalName, @{Name="LastSignIn";Expression={$_.SignInActivity.LastSignInDateTime}} |
Export-Csv -Path "DernieresConnexions.csv" -NoTypeInformation -Encoding UTF8

🛠️ Script de création d’utilisateurs en masse

Script

# Installation et connexion Microsoft Graph
if (!(Get-Module -ListAvailable -Name Microsoft.Graph)) {
    Write-Host "Installation du module Microsoft.Graph..." -ForegroundColor Green
    Install-Module -Name Microsoft.Graph -Force -Scope CurrentUser
}
 
# Installation module ImportExcel pour traiter le CSV
if (!(Get-Module -ListAvailable -Name ImportExcel)) {
    Write-Host "Installation du module ImportExcel..." -ForegroundColor Green
    Install-Module -Name ImportExcel -Force -Scope CurrentUser
}
 
# Connexion avec les permissions nécessaires
Write-Host "Connexion à Microsoft Graph..." -ForegroundColor Green
Connect-MgGraph -Scopes "User.ReadWrite.All", "Group.ReadWrite.All"
 
# Configuration générale (à adapter selon votre environnement)
$csvPath = "C:\temp\NouveauxUtilisateurs.csv"
$logPath = "C:\temp\creation_utilisateurs_log.txt"
$domainePrincipal = "monentreprise.com"
$departementDefaut = "IT"
$paysDefaut = "France"
$usageLocation = "FR"
 
# Créer le fichier de log
New-Item -Path $logPath -ItemType File -Force
Write-Host "Fichier de log créé : $logPath" -ForegroundColor Yellow
 
# Importer les données CSV (colonnes attendues : FirstName, LastName, JobTitle, Department)
if (Test-Path $csvPath) {
    $utilisateurs = Import-Csv -Path $csvPath -Delimiter ";"
    Write-Host "Fichier CSV importé : $($utilisateurs.Count) utilisateurs trouvés" -ForegroundColor Green
} else {
    Write-Host "Fichier CSV non trouvé : $csvPath" -ForegroundColor Red
    exit
}
 
# Fonction pour générer un mot de passe sécurisé
function New-RandomPassword {
    param([int]$Length = 12)
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%"
    return -join ((1..$Length) | ForEach-Object { $chars[(Get-Random -Maximum $chars.Length)] })
}
 
# Boucle de création des utilisateurs
foreach ($user in $utilisateurs) {
    # Vérifications des champs obligatoires
    if ([string]::IsNullOrWhiteSpace($user.FirstName) -or [string]::IsNullOrWhiteSpace($user.LastName)) {
        $message = "ERREUR: Prénom ou nom manquant pour l'utilisateur ligne $($utilisateurs.IndexOf($user) + 2)"
        Write-Host $message -ForegroundColor Red
        Add-Content -Path $logPath -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $message"
        continue
    }
 
    # Génération des informations utilisateur
    $prenom = $user.FirstName.Trim()
    $nom = $user.LastName.Trim()
    $nomComplet = "$prenom $nom"
    $mailNickname = "$($prenom.ToLower()).$($nom.ToLower())"
    $email = "$mailNickname@$domainePrincipal"
    $motDePasse = New-RandomPassword
    $poste = if (![string]::IsNullOrWhiteSpace($user.JobTitle)) { $user.JobTitle } else { "Utilisateur" }
    $service = if (![string]::IsNullOrWhiteSpace($user.Department)) { $user.Department } else { $departementDefaut }
 
    Write-Host "Création de l'utilisateur : $nomComplet ($email)" -ForegroundColor Cyan
 
    try {
        # Vérifier si l'utilisateur existe déjà
        $existingUser = Get-MgUser -Filter "UserPrincipalName eq '$email'" -ErrorAction SilentlyContinue
        if ($existingUser) {
            $message = "ATTENTION: L'utilisateur $email existe déjà"
            Write-Host $message -ForegroundColor Yellow
            Add-Content -Path $logPath -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $message"
            continue
        }
 
        # Création de l'utilisateur
        $passwordProfile = @{
            Password = $motDePasse
            ForceChangePasswordNextSignIn = $true
        }
 
        $nouveauUtilisateur = @{
            DisplayName = $nomComplet
            UserPrincipalName = $email
            MailNickname = $mailNickname
            GivenName = $prenom
            Surname = $nom
            JobTitle = $poste
            Department = $service
            Country = $paysDefaut
            UsageLocation = $usageLocation
            PasswordProfile = $passwordProfile
            AccountEnabled = $true
        }
 
        $userCreated = New-MgUser @nouveauUtilisateur
 
        # Log de succès avec mot de passe
        $successMessage = "SUCCESS: Utilisateur $nomComplet créé | Email: $email | Mot de passe: $motDePasse"
        Write-Host "✓ Utilisateur créé avec succès" -ForegroundColor Green
        Add-Content -Path $logPath -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $successMessage"
 
        # Pause pour éviter les limitations de taux
        Start-Sleep -Milliseconds 500
 
    } catch {
        # Log d'erreur
        $errorMessage = "ERREUR: Échec création $nomComplet ($email) - $($_.Exception.Message)"
        Write-Host "✗ Erreur lors de la création: $($_.Exception.Message)" -ForegroundColor Red
        Add-Content -Path $logPath -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $errorMessage"
    }
}
 
Write-Host "`n=== RÉSUMÉ ===" -ForegroundColor Magenta
Write-Host "Script terminé. Consultez le fichier de log pour les détails : $logPath" -ForegroundColor Yellow
Write-Host "Pour assigner des licences, utilisez : Set-MgUserLicense" -ForegroundColor Yellow
 
# Déconnexion
Disconnect-MgGraph

Format CSV attendu

Créez un fichier CSV avec ces colonnes (séparateur ;) :

FirstName;LastName;JobTitle;Department
Jean;Dupont;Administrateur Système;IT
Marie;Martin;Développeuse;IT
Pierre;Durant;Chef de projet;Marketing
Sophie;Bernard;Comptable;Finance

Points clés du script

  • 🔒 Sécurisé : Génération de mots de passe aléatoires robustes
  • 📝 Logging complet : Tous les succès/échecs sont tracés
  • Limitation de débit : Pause entre créations pour éviter les erreurs API
  • 🔍 Vérifications : Contrôle si l’utilisateur existe avant création

🎫 Licences

Attribution de licences

# Voir les licences disponibles
Get-MgSubscribedSku
 
# Définir la localisation (obligatoire)
Update-MgUser -UserId "john@domain.com" -UsageLocation "FR"
 
# Attribuer une licence
$SkuId = (Get-MgSubscribedSku | Where-Object {$_.SkuPartNumber -eq "SPE_E3"}).SkuId
Set-MgUserLicense -UserId "john@domain.com" -AddLicenses @(@{SkuId=$SkuId}) -RemoveLicenses @()