Checking Guest User Sign-In Activity with Graph PowerShell

Monitoring guest user sign-in activity is crucial for maintaining security and ensuring proper access management within your Microsoft 365 environment. With the Microsoft Graph PowerShell module, you can efficiently track and report on guest user sign-ins. This article will guide you through a PowerShell script that checks guest user sign-in activity and exports the results to a CSV file.


PowerShell Script for Checking Guest User Sign-In Activity

Below is the PowerShell script that retrieves guest user sign-in activity for the past 30 days and exports the data to a CSV file:

# Install the Microsoft Graph PowerShell module if not already installed
# Install-Module Microsoft.Graph -Scope CurrentUser

# Import the Microsoft Graph module
Import-Module Microsoft.Graph

# Authenticate to Microsoft Graph
Connect-MgGraph -Scopes "AuditLog.Read.All" "User.Read.All" "Directory.Read.All"

# Define the date range for checking sign-in activity (e.g. last 30 days)
$startDate = (Get-Date).AddDays(-30).ToString("yyyy-MM-ddTHH:mm:ssZ")
$endDate = (Get-Date).ToString("yyyy-MM-ddTHH:mm:ssZ")

# Get all guest users
$guestUsers = Get-MgUser -Filter "UserType eq 'Guest'" -All

# Initialize an array to store guest user sign-in activity
$guestUserSignInActivities = @()

# Check if any guest users exist
if ($guestUsers.Count -eq 0) {
    Write-Host "No guest users found."
} else {
    # Loop through each guest user and get their sign-in activity
    foreach ($guestUser in $guestUsers) {
        $userId = $guestUser.Id
        $signInActivities = Get-MgAuditLogSignIn -Filter "userId eq '$userId' and createdDateTime ge $startDate and createdDateTime le $endDate" -All

        if ($signInActivities) {
            foreach ($activity in $signInActivities) {
                $guestUserSignInActivities += [PSCustomObject]@{
                    UserId             = $guestUser.Id
                    UserPrincipalName  = $guestUser.UserPrincipalName
                    DisplayName        = $guestUser.DisplayName
                    SignInDateTime     = $activity.createdDateTime
                    Status             = $activity.status.additionalDetails
                }
            }
        }
    }

    # Export the guest user sign-in activities to a CSV file
    $guestUserSignInActivities | Export-Csv -Path "GuestUserSignInActivities.csv" -NoTypeInformation

    # Output the results to the console
    $guestUserSignInActivities | Format-Table -AutoSize

How the Script Works

The script works as follows:

  • Module Installation and Import: The script begins by ensuring the Microsoft Graph PowerShell module is installed and imported. If not already installed, uncomment the Install-Module line.
  • Authentication: The script authenticates to Microsoft Graph with the required permissions (AuditLog.Read.All, User.Read.All, and Directory.Read.All).
  • Date Range Definition: The date range is set to the last 30 days to filter sign-in activities within this period.
  • Fetching Guest Users: The script retrieves all guest users in the Microsoft 365 environment using the Get-MgUser cmdlet with a filter for guest users.
  • Checking for Guest Users: A check is performed to ensure there are guest users before proceeding.
  • Retrieving Sign-In Activity: For each guest user, the script retrieves their sign-in activity using the Get-MgAuditLogSignIn cmdlet. The results are stored in a custom object.
  • Exporting and Displaying Results: The sign-in activity data is exported to a CSV file named GuestUserSignInActivities.csv and displayed in the console.

Tips for Improving the Script

  • Error Handling: Add error handling to manage potential issues such as network errors or insufficient permissions.
  • try {
        # Code to fetch sign-in activities
    } catch {
        Write-Host "An error occurred: $_"
    }
  • Email Notifications: Enhance the script to send email notifications if specific conditions are met, such as no sign-in activity or failed sign-ins.
  • # Send email notification if no sign-in activity
    if ($guestUserSignInActivities.Count -eq 0) {
        Send-MailMessage -To "admin@domain.com" -Subject "No Guest User Sign-In Activity" -Body "No sign-ins detected for guest users in the past 30 days."
    }
  • Scheduled Task: Set up the script as a scheduled task to run periodically and automatically generate reports.
  • Detailed Reporting: Include more details in the report, such as the sign-in location, client app used, and conditional access policies applied.

Conclusion

Tracking guest user sign-in activity is vital for ensuring the security and proper management of your Microsoft 365 environment. This PowerShell script provides a simple yet effective way to monitor and report on guest user sign-ins. By implementing the suggested improvements, you can enhance the script's functionality and make it a powerful tool for your IT management toolkit.


Related Articles:

Using Get-MgDirectoryRole in Graph PowerShell
Using Get-MgUserLicenseDetail in Graph PowerShell
Using Find-GraphMgCommand in Graph PowerShell
Connect to Microsoft 365 Using PowerShell
How to Create Bulk Users in Office 365 Using Graph PowerShell?
Create Microsoft 365 Group Using Microsoft Graph PowerShell
Block Microsoft 365 User Using Microsoft Graph PowerShell
Assign Microsoft 365 License Using Graph PowerShell
Microsoft 365 User Management Using Graph PowerShell
Checking Group Membership in Microsoft 365
Bulk Assign Microsoft 365 License
Find Inactive Users in Microsoft 365
Using Powershell Graph Search Query
Using Powershell Graph Filter Query
Using Where-Object In Graph PowerShell
Using Expand Property In Graph PowerShell
Using Select Object In Graph PowerShell
Using -Contains Operator In Graph PowerShell
Add User to Multiple Microsoft 365 Groups Using Graph PowerShell
Get Microsoft 365 User Location Using Graph PowerShell
Import Microsoft 365 Groups from CSV File Using Graph PowerShell
Microsoft 365 Group User Import Using Graph PowerShell

© m365corner.com. All Rights Reserved. Design by HTML Codex