Microsoft Entra ID kullanıcılarını PowerShell ile CSV'ye aktarın


Microsoft Entra ID kullanıcı bilgilerini PowerShell ile CSV'ye aktarmak istiyoruz. Microsoft Entra ID kullanıcılarını neden PowerShell ile listelememiz gerekiyor? Örneğin her Microsoft Entra ID kullanıcısının doğru niteliklere sahip olup olmadığını bilmek istiyoruz. Çünkü hizmet masasının bu bilgiye ihtiyacı var. Bu yazımızda Microsoft Entra ID kullanıcılarını PowerShell ile CSV dosyasına nasıl aktaracağınızı öğreneceksiniz.

Bilgi aktarımı Microsoft Entra ID kullanıcıları PowerShell betiği

Export-EntraIDUsers.ps1 PowerShell betiği Microsoft Entra kiracısına karşı çalışacaktır. Bundan sonra raporu CSV dosyasına aktaracaktır. CSV dosyasını Microsoft Excel veya CSV dosya uzantısını destekleyen başka bir uygulamayla açabilirsiniz.

Komut dosyası, kullanıcı başına aşağıdaki bilgileri toplayacaktır:

  1. İD
  2. İlk adı
  3. Soy isim
  4. Ekran adı
  5. Kullanıcı asıl adı
  6. Alan adı
  7. E-posta adresi
  8. İş unvanı
  9. Yönetici görünen adı
  10. Yönetici kullanıcı asıl adı
  11. Departman
  12. Şirket
  13. Ofis
  14. Çalışan Kimliği
  15. Mobil
  16. Telefon
  17. Sokak
  18. Şehir
  19. Posta Kodu
  20. Durum
  21. Ülke
  22. Kullanıcı türü
  23. Şirket içi senkronizasyon
  24. Hesap durumu
  25. Hesap şu tarihte oluşturuldu:
  26. Son başarılı oturum açma (Microsoft Entra ID P1/P2 lisansı gerektirir)
  27. Lisanslı
  28. MFA durumu (kimlik doğrulama yöntemleri dahil)

Microsoft Entra ID kullanıcılarını PowerShell ile CSV'ye aktarın

Adımları inceleyelim ve Microsoft Entra ID kullanıcılarını PowerShell ile CSV dosyasına aktaralım.

1. Adım. Microsoft Graph PowerShell'i yükleyin

Windows PowerShell'i yönetici olarak çalıştırın ve Microsoft Graph PowerShell'i yükleyin.

Install-Module Microsoft.Graph -Force
Install-Module Microsoft.Graph.Beta -AllowClobber -Force

Önemli: Her zaman Microsoft Graph PowerShell ve Microsoft Graph Beta PowerShell modüllerini yükleyin. Bunun nedeni, bazı cmdlet'lerin henüz son sürümde mevcut olmaması ve çalışmayacak olmasıdır. Hataları ve yanlış sonuçları önlemek için bir cmdlet'i veya betiği çalıştırmadan önce her iki modülü de en son sürüme güncelleyin.

2. Adım. Microsoft Graph PowerShell'e bağlanın

Microsoft Graph PowerShell ile Microsoft Entra'ya bağlanın.

Connect-MgGraph -Scopes "User.Read.All", "UserAuthenticationMethod.Read.All", "AuditLog.Read.All"

Genel yönetici kimlik bilgilerinizi girin ve Microsoft Graph izin isteğini kabul edin.

3. Adım. Microsoft Entra ID kullanıcıları PowerShell betiğini dışa aktarmaya hazırlayın

(C:) sürücüsünde iki klasör oluşturun:

  • Sıcaklık
  • Komut dosyaları

Export-EntraIDUsers.ps1 PowerShell betiğini indirin ve C:\scripts klasörüne yerleştirin. Komut dosyası, CSV dosyasını C:\temp klasörüne aktaracaktır.

Komut dosyasını çalıştırırken hataları önlemek için dosyanın engellemesinin kaldırıldığından emin olun. PowerShell betiğini çalıştırırken dijital olarak imzalanmamış hata makalesinde daha fazlasını okuyun.

Diğer bir seçenek de aşağıdaki kodu kopyalayıp Not Defteri'ne yapıştırmaktır. Ona Export-EntraIDUsers.ps1 adını verin ve C:\scripts klasörüne yerleştirin.

<#
    .SYNOPSIS
    Export-EntraIDUsers.ps1

    .DESCRIPTION
    Export Microsoft Entra ID users to CSV file.

    .LINK
    www.alitajran.com/export-microsoft-entra-id-users-to-csv-powershell

    .NOTES
    Written by: ALI TAJRAN
    Website:    www.alitajran.com
    LinkedIn:   linkedin.com/in/alitajran

    .CHANGELOG
    V1.10, 06/20/2023 - Initial version
    V1.10, 06/21/2023 - Added license status and MFA status including methods
    V1.20, 06/22/2023 - Added progress bar and last sign in date
    V1.30, 07/24/2023 - Update for Microsoft Graph PowerShell changes
    V1.40, 04/07/2024 - Added domain name
#>

# Connect to Microsoft Graph API
Connect-MgGraph -Scopes "User.Read.All", "UserAuthenticationMethod.Read.All", "AuditLog.Read.All"

# Create variable for the date stamp
$LogDate = Get-Date -f yyyyMMddhhmm

# Define CSV file export location variable
$Csvfile = "C:\temp\AllEntraIDUsers_$LogDate.csv"

# Retrieve users using the Microsoft Graph API with property
$propertyParams = @{
    All            = $true
    # Uncomment below if you have Microsoft Entra ID P1/P2 to get last sign in date
    # Property = 'SignInActivity'
    ExpandProperty = 'manager'
}

$users = Get-MgBetaUser @propertyParams
$totalUsers = $users.Count

# Initialize progress counter
$progress = 0

# Initialize an array to store user objects
$userObjects = @()

# Loop through all users and collect user objects
foreach ($index in 0..($totalUsers - 1)) {
    $user = $users[$index]

    # Update progress counter
    $progress++

    # Calculate percentage complete
    $percentComplete = ($progress / $totalUsers) * 100

    # Define progress bar parameters
    $progressParams = @{
        Activity        = "Processing Users"
        Status          = "User $($index + 1) of $totalUsers - $($user.userPrincipalName) - $($percentComplete -as [int])% Complete"
        PercentComplete = $percentComplete
    }

    # Display progress bar
    Write-Progress @progressParams

    # Get manager information
    $managerDN = $user.Manager.AdditionalProperties.displayName
    $managerUPN = $user.Manager.AdditionalProperties.userPrincipalName

    # Create an object to store user properties
    $userObject = [PSCustomObject]@{
        "ID"                          = $user.id
        "First name"                  = $user.givenName
        "Last name"                   = $user.surname
        "Display name"                = $user.displayName
        "User principal name"         = $user.userPrincipalName
        "Domain name"                 = $user.userPrincipalName.Split('@')[1]
        "Email address"               = $user.mail
        "Job title"                   = $user.jobTitle
        "Manager display name"        = $managerDN
        "Manager user principal name" = $managerUPN
        "Department"                  = $user.department
        "Company"                     = $user.companyName
        "Office"                      = $user.officeLocation
        "Employee ID"                 = $user.employeeID
        "Mobile"                      = $user.mobilePhone
        "Phone"                       = $user.businessPhones -join ','
        "Street"                      = $user.streetAddress
        "City"                        = $user.city
        "Postal code"                 = $user.postalCode
        "State"                       = $user.state
        "Country"                     = $user.country
        "User type"                   = $user.userType
        "On-Premises sync"            = if ($user.onPremisesSyncEnabled) { "enabled" } else { "disabled" }
        "Account status"              = if ($user.accountEnabled) { "enabled" } else { "disabled" }
        "Account Created on"          = $user.createdDateTime
        # Uncomment below if you have Microsoft Entra ID P1/P2 to get last succesful sign in date
        # "Last sign in"                 = if ($user.SignInActivity.LastSuccessfulSignInDateTime) { $user.SignInActivity.LastSuccessfulSignInDateTime } else { "No sign in" }
        "Licensed"                    = if ($user.assignedLicenses.Count -gt 0) { "Yes" } else { "No" }
        "MFA status"                  = "-"
        "Email authentication"        = "-"
        "FIDO2 authentication"        = "-"
        "Microsoft Authenticator App" = "-"
        "Password authentication"     = "-"
        "Phone authentication"        = "-"
        "Software Oath"               = "-"
        "Temporary Access Pass"       = "-"
        "Windows Hello for Business"  = "-"
    }

    $MFAData = Get-MgBetaUserAuthenticationMethod -UserId $user.userPrincipalName

    # Check authentication methods for each user
    foreach ($method in $MFAData) {
        Switch ($method.AdditionalProperties["@odata.type"]) {
            "#microsoft.graph.emailAuthenticationMethod" {
                $userObject."Email authentication" = $true
                $userObject."MFA status" = "Enabled"
            }
            "#microsoft.graph.fido2AuthenticationMethod" {
                $userObject."FIDO2 authentication" = $true
                $userObject."MFA status" = "Enabled"
            }
            "#microsoft.graph.microsoftAuthenticatorAuthenticationMethod" {
                $userObject."Microsoft Authenticator App" = $true
                $userObject."MFA status" = "Enabled"
            }
            "#microsoft.graph.passwordAuthenticationMethod" {
                $userObject."Password authentication" = $true
                # When only the password is set, then MFA is disabled.
                if ($userObject."MFA status" -ne "Enabled") {
                    $userObject."MFA status" = "Disabled"
                }
            }
            "#microsoft.graph.phoneAuthenticationMethod" {
                $userObject."Phone authentication" = $true
                $userObject."MFA status" = "Enabled"
            }
            "#microsoft.graph.softwareOathAuthenticationMethod" {
                $userObject."Software Oath" = $true
                $userObject."MFA status" = "Enabled"
            }
            "#microsoft.graph.temporaryAccessPassAuthenticationMethod" {
                $userObject."Temporary Access Pass" = $true
                $userObject."MFA status" = "Enabled"
            }
            "#microsoft.graph.windowsHelloForBusinessAuthenticationMethod" {
                $userObject."Windows Hello for Business" = $true
                $userObject."MFA status" = "Enabled"
            }
        }
    }

    # Add user object to the array
    $userObjects += $userObject
}

# Complete the progress bar
Write-Progress -Activity "Processing Users" -Completed

# Export all user objects to CSV
$userObjects | Sort-Object "Display name" | Export-Csv -Path $Csvfile -NoTypeInformation -Encoding UTF8 #-Delimiter ";"

Bu şekilde görünüyor.

4. Adım. Microsoft Entra ID kullanıcıları PowerShell betiğini dışa aktarmayı çalıştırın

Microsoft Entra ID kullanıcılarını CSV dosyasına aktarmak için PowerShell betiğini çalıştırın. Tamamlanana kadar bekleyin.

C:\scripts\.\Export-EntraIDUsers.ps1

5. Adım. Microsoft Entra ID kullanıcılarının CSV dosyasını rapor ettiğini doğrulayın

temp klasörüne gidin ve AllEntraIDUsers_ dosyasını gördüğünüzü doğrulayın.

CSV dosyasını favori uygulamanızla açın. Örneğimizde Microsoft Excel var.

Her şey harika görünüyor!

Devamını oku: Microsoft Entra Connect'i yeni sunucuya geçirme »

Çözüm

Microsoft Entra ID kullanıcılarını PowerShell ile CSV'ye nasıl aktaracağınızı öğrendiniz. Her kullanıcı hesabında çok fazla bilgi vardır. PowerShell ile ihtiyaçlarınıza uygun özel bir rapora sahip olabilirsiniz.

Bu makaleyi beğendiniz mi? Ayrıca Microsoft Entra Connect hesaplarını bulmayı da beğenebilirsiniz. Bizi takip etmeyi ve bu makaleyi paylaşmayı unutmayın.

İlgili makaleler