Managing and auditing guest users in Microsoft 365 is an important task for administrators. Automating this process with Graph PowerShell can significantly streamline your administration tasks. Below is a detailed script to fetch and generate a report of all guest users in your Microsoft 365 environment, including their Display Name, User Principal Name, and Invitation Status.
# Install the Microsoft.Graph module if not already installed
Install-Module -Name Microsoft.Graph -Force -AllowClobber
# Connect to Microsoft 365
Connect-MgGraph -Scopes "User.Read.All"
# Define the output CSV file path
$outputFile = "C:\Reports\GuestUsersReport.csv"
# Initialize an array to store guest user details
$guestUsersReport = @()
# Get all guest users
$guestUsers = Get-MgUser -Filter "UserType eq 'Guest'" -All -Property DisplayName, UserPrincipalName, ExternalUserState
# Process each guest user
foreach ($guestUser in $guestUsers) {
$guestUserDetails = [PSCustomObject]@{
DisplayName = $guestUser.DisplayName
UserPrincipalName = $guestUser.UserPrincipalName
InvitationStatus = $guestUser.ExternalUserState
}
$guestUsersReport += $guestUserDetails
}
# Export the report to a CSV file
$guestUsersReport | Export-Csv -Path $outputFile -NoTypeInformation
Write-Output "Guest users report generated: $outputFile"
# Disconnect from Microsoft 365
Disconnect-MgGraph
The CSV file output by the script should look like this:
Prerequisites:
Connect-MgGraph
command initiates a connection to Microsoft 365 with the required scopes for reading user information, namely User.Read.All.Define Output File:
Initialize Array:
Get Guest Users:
Get-MgUser
cmdlet with the filter UserType eq 'Guest'
.Process Each Guest User:
Export Report:
Export-Csv
cmdlet.Disconnect:
Disconnect-MgGraph
command ends the session with Microsoft 365.Send-MailMessage
cmdlet to send the CSV file as an attachment.Automating the retrieval of guest users using Graph PowerShell simplifies administrative tasks, saving time and reducing the potential for human error. This script provides a straightforward way to generate comprehensive reports on guest users, ensuring you have up-to-date information on who has access to your Microsoft 365 environment.
By further enhancing the script, you can add more functionalities and make it an even more powerful tool in your administrative toolkit. Embrace automation and streamline your Microsoft 365 management with the power of Graph PowerShell!
© m365corner.com. All Rights Reserved. Design by HTML Codex