<# .SYNOPSIS Exports all active Entra ID users and their attributes to a CSV file. .DESCRIPTION Connects to Microsoft Graph, retrieves all users where AccountEnabled is true, and exports every available attribute to a timestamped CSV file in an \Exports subfolder. .PARAMETER ExportPath The subfolder name where the CSV will be saved. Defaults to 'Exports'. .EXAMPLE Export-EntraActiveUsers #> function Export-EntraActiveUsers { [CmdletBinding()] param ( [Parameter(Mandatory = $false)] [string]$ExportPathName = "Exports" ) process { Set-StrictMode -Version Latest # 1. Setup Paths and Directories $BasePath = $PSScriptRoot if ([string]::IsNullOrWhiteSpace($BasePath)) { $BasePath = Get-Location } $TargetDirectory = Join-Path -Path $BasePath -ChildPath $ExportPathName $Timestamp = Get-Date -Format "yyyyMMdd-HHmm" $FileName = "EntraID_ActiveUsers_$Timestamp.csv" $FullFilePath = Join-Path -Path $TargetDirectory -ChildPath $FileName try { Write-Verbose "Ensuring directory exists: $TargetDirectory" if (-not (Test-Path -Path $TargetDirectory)) { New-Item -Path $TargetDirectory -ItemType Directory -Force | Out-Null } # 2. Check for Microsoft Graph Connection Write-Verbose "Checking Microsoft Graph connection..." $CurrentContext = Get-MgContext if (-not $CurrentContext) { throw "No active Microsoft Graph connection found. Please run 'Connect-MgGraph' first." } # 3. Retrieve Active Users # We filter for AccountEnabled eq true and select all properties (*) Write-Verbose "Fetching active users from Entra ID..." $UserFilter = "accountEnabled eq true" # Using -All to ensure we bypass the default page size limits $Users = Get-MgUser -All -Filter $UserFilter ` -Property Id, UserPrincipalName, GivenName, Surname, DisplayName, Mail, MobilePhone, CompanyName, JobTitle, EmployeeId, FaxNumber, OfficeLocation -ErrorAction Stop | ` Select-Object Id, UserPrincipalName, GivenName, Surname, DisplayName, Mail, MobilePhone, CompanyName, JobTitle, EmployeeId, FaxNumber, OfficeLocation if ($null -eq $Users -or $Users.Count -eq 0) { Write-Warning "No active users found in the tenant." return } Write-Verbose "Found $($Users.Count) users. Exporting to $FullFilePath..." # 4. Export to CSV $Users | Export-Csv -Path $FullFilePath -NoTypeInformation -Encoding utf8 Write-Output "Export successfully completed: $FullFilePath" } catch { Write-Error "An error occurred during export: $($_.Exception.Message)" } } }