-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathEntraIDGuestUsersExport.ps1
More file actions
161 lines (134 loc) · 5.6 KB
/
EntraIDGuestUsersExport.ps1
File metadata and controls
161 lines (134 loc) · 5.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
<#
.SYNOPSIS
Export guest users from Microsoft Entra ID (Azure AD) with detailed information, such as last login and account creation dates.
.DESCRIPTION
This script connects to Microsoft Graph API to retrieve all guest users (`userType eq 'Guest'`) in Azure AD.
It extracts the following information:
- DisplayName (properly escaped if it contains commas or special characters)
- Email
- Account creation date
- Days since account creation (if never logged in)
- Last login date
- Days since last login
The results are exported to a user-specified CSV file.
.PARAMETER None
No additional parameters are required. The script will prompt for the file save location.
.NOTES
Version: 1.0.0
.REQUIREMENTS
Before running the script, ensure you meet the following requirements:
- Microsoft Entra ID (formerly Azure AD) – Your account must be linked to an Entra ID tenant.
- Admin Role – Requires User.Read.All or higher permissions in Entra ID.
- Microsoft Graph PowerShell Module – Installed automatically by the script if missing.
- PowerShell Execution Policy – Must allow script execution (Set-ExecutionPolicy RemoteSigned).
Open PowerShell with elevated permissions (Run as Administrator).
Run the script using:
.\EntraIDGuestUsersExport.ps1
#>
# Ensure the script stops on errors
$ErrorActionPreference = "Stop"
# Function to display messages with timestamps
function Write-Log {
param([string]$Message)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host "[$timestamp] $Message" -ForegroundColor Cyan
}
# Function to escape fields with special characters (e.g., commas)
function Escape-CsvField {
param([string]$FieldValue)
if ($FieldValue -and $FieldValue.Contains(",")) {
return "`"$FieldValue`"" # Wrap the field in double quotes
} else {
return $FieldValue
}
}
Write-Log "Starting Entra ID Guest User Export..."
# Prompt user to select a save location for the CSV file
Write-Log "Please choose where to save the output CSV file..."
$FileBrowser = New-Object -ComObject Shell.Application
$Folder = $FileBrowser.BrowseForFolder(0, "Select Folder to Save CSV File", 0)
if ($Folder) {
$outputFolder = $Folder.Self.Path
$outputFile = "$outputFolder\EntraIDGuestUsers_LastSignIn.csv"
} else {
Write-Host "No folder selected. Using default script directory." -ForegroundColor Yellow
$outputFile = "$PSScriptRoot\EntraIDGuestUsers_LastSignIn.csv"
}
Write-Log "CSV File will be saved as: $outputFile"
# Check if Microsoft Graph Users module is installed
if (-not (Get-Module -ListAvailable -Name Microsoft.Graph.Users)) {
Write-Log "Microsoft Graph module not found. Installing now..."
Install-Module Microsoft.Graph -Scope CurrentUser -Force
}
# Import only required Microsoft Graph submodule
Import-Module Microsoft.Graph.Users
# Connect to Microsoft Graph
Write-Log "Connecting to Microsoft Graph API..."
try {
Connect-MgGraph -Scopes "User.Read.All" -ErrorAction Stop
Write-Log "Connected successfully to Microsoft Graph."
} catch {
Write-Host "ERROR: Failed to connect to Microsoft Graph. Ensure you have the correct permissions." -ForegroundColor Red
exit
}
# Fetch all guest users with additional properties
Write-Log "Retrieving guest users from Microsoft Entra ID (Azure AD)..."
try {
$guestUsers = Get-MgUser -Filter "userType eq 'Guest'" -Property Id, DisplayName, Mail, SignInActivity, CreatedDateTime -All
Write-Log "Retrieved $($guestUsers.Count) guest users."
} catch {
Write-Host "ERROR: Failed to retrieve guest users. Ensure you have the necessary permissions." -ForegroundColor Red
exit
}
# Initialize an array to store the results
$results = @()
# Get the current date for calculation
$today = Get-Date
Write-Log "Processing users and cleaning data..."
foreach ($user in $guestUsers) {
# Extract and clean data
$displayName = if ($user.DisplayName) {
Escape-CsvField($user.DisplayName.Trim() -replace "\s+", " ") # Normalize spaces and wrap if needed
} else {
"Unknown Name"
}
$email = if ($user.Mail) {
Escape-CsvField($user.Mail.Trim()) # Wrap email if it contains commas
} else {
"No Email Provided"
}
$createdDate = $user.CreatedDateTime
$lastSignInDate = $user.SignInActivity.LastSignInDateTime
# Calculate days since last login or creation
$daysSinceLastLogin = if ($lastSignInDate) {
($today - $lastSignInDate).Days
} else {
"Never Logged In"
}
$daysSinceCreation = if (!$lastSignInDate -and $createdDate) {
($today - $createdDate).Days
} else {
""
}
# Add a clean record to the results array
$results += [PSCustomObject]@{
DisplayName = $displayName
Email = $email
CreatedDate = if ($createdDate) { $createdDate.ToString("dd-MM-yyyy HH:mm") } else { "Unknown" }
DaysSinceCreation = if ($daysSinceCreation -ne "") { $daysSinceCreation } else { "N/A" }
LastSignIn = if ($lastSignInDate) { $lastSignInDate.ToString("dd-MM-yyyy HH:mm") } else { "Never Logged In" }
DaysSinceLastLogin = $daysSinceLastLogin
}
}
# Export results to CSV
Write-Log "Exporting data to CSV file..."
try {
$results | Export-Csv -Path $outputFile -NoTypeInformation
Write-Log "Export completed successfully! File saved as: $outputFile"
} catch {
Write-Host "ERROR: Failed to save the CSV file. Check file permissions." -ForegroundColor Red
}
# Disconnect from Microsoft Graph
Write-Log "Disconnecting from Microsoft Graph API..."
Disconnect-MgGraph
Write-Log "Script completed!"