Disabling Microsoft 365 Guest User Accounts Using Graph PowerShell

In a dynamic working environment, it’s crucial to manage guest user accounts effectively, especially when a project ends or a security issue arises. Disabling guest accounts ensures that only authorized users have access to your organization's resources. This article provides a simple PowerShell script that uses Microsoft Graph to disable guest user accounts in Microsoft 365.


Script to Disable Guest User Accounts

Here’s a PowerShell script that reads a list of guest user email addresses from a CSV file and disables their accounts:

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

# Connect to Microsoft Graph with appropriate scopes
Connect-MgGraph -Scopes "User.ReadWrite.All"

# Function to disable guest user accounts
function Disable-GuestUsers {
    # Path to the CSV file with guest user email addresses
    $csvPath = "C:\path\to\guest_users.csv"
    
    # Import guest user emails from CSV
    $guestUsers = Import-Csv -Path $csvPath

    # Loop through each guest user
    foreach ($user in $guestUsers) {
        try {
            # Get the user by email
            $guestUser = Get-MgUser -Filter "UserPrincipalName eq '$($user.Email)'"

            if ($guestUser) {
                # Disable the account using -BodyParameter
                $params = @{
                    accountEnabled = $false
                }
                Update-MgUser -UserId $guestUser.Id -BodyParameter $params
                Write-Host "Disabled guest user: $($user.Email)"
            } else {
                Write-Warning "Guest user not found: $($user.Email)"
            }
        } catch {
            Write-Error "Failed to update status for user: $($user.Email). Error: $_"
        }
    }
}

# Disable guest users
Disable-GuestUsers

# Disconnect from Microsoft Graph
Disconnect-MgGraph

CSV File Format for User Upload

The CSV file should contain the following structure:

Email
guestuser1@example.com
guestuser2@example.com
guestuser3@example.com

Each guest user's email address is listed under the "Email" column. Save this file with a .csv extension, such as guest_users.csv


Script Output


How the Script Works

The script works as follows:

  • Importing the Module: The script starts by importing the Microsoft.Graph.Users module which provides the necessary cmdlets to interact with Microsoft Graph.
  • Connecting to Microsoft Graph: It then connects to Microsoft Graph using the Connect-MgGraph cmdlet requesting the "User.ReadWrite.All" scope to gain permissions to read and write user information.
  • Defining the Function: The Disable-GuestUsers function is defined which contains the core logic of the script.
  • Reading the CSV File: The script reads a CSV file containing the email addresses of the guest users to be disabled. The CSV file should have a single column named Email.
  • Looping Through Users: For each user email in the CSV file, the script retrieves the user object from Microsoft Graph using the Get-MgUser cmdlet with a filter based on the user's email address.
  • Disabling the Account: If the user is found, the script constructs a parameters object ($params) with accountEnabled set to $false. It then updates the user account using the Update-MgUser cmdlet with the -BodyParameter parameter.
  • Handling Errors: The script includes error handling to catch and display any issues that occur during the process.
  • Disconnecting from Microsoft Graph: Finally, the script disconnects from Microsoft Graph to clean up the session.

Improving the Script Further

  • Logging: Add logging to track which accounts were successfully disabled and which ones encountered errors. This can be done by writing output to a log file.
  • try {
        # Code to fetch sign-in activities
    } catch {
        Write-Host "An error occurred: $_"
    }
  • Input Validation: Implement input validation to check if the CSV file exists and contains valid email addresses before proceeding with the script.
  • Enable Option: Extend the script to include an option to enable guest accounts, similar to the disable function, for more flexible account management.
  • Notification: Include functionality to send email notifications to administrators when guest accounts are disabled, providing an audit trail and alerting relevant parties.
  • # 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."
    }
  • Error Reporting: Enhance error handling to capture specific errors and provide more detailed reporting, which can help in troubleshooting issues more effectively.
  • Automation: Schedule the script to run automatically using Windows Task Scheduler or Azure Automation to ensure guest accounts are regularly reviewed and managed without manual intervention.

Possible Errors and Solutions

While executing the script to disable guest user accounts, you may encounter certain errors. Below are common issues and their resolutions

Error Message Cause Solution
Authorization_RequestDenied Insufficient permissions to perform the operation. Ensure that the account used to connect to Microsoft Graph has the necessary permissions, such as User.ReadWrite.All. Additionally, verify that the account has the appropriate administrative roles assigned in Azure Active Directory.
Guest user not found The script couldn't locate a guest user with the provided email address. Confirm that the email addresses in the CSV file are correct and correspond to existing guest user accounts in your Microsoft 365 tenant. Ensure there are no typographical errors or missing entries.
Failed to update status for user An unexpected error occurred while attempting to disable the user account. Review the detailed error message provided in the script's output. Common issues include network connectivity problems, temporary service outages, or insufficient permissions. Retry the operation after resolving any identified issues.
Import-Csv: Could not find file The script cannot locate the specified CSV file. Verify that the path to the CSV file is correct and that the file exists at the specified location. Ensure that the script has the necessary permissions to access the file.
Connect-MgGraph: AADSTS7000215: Invalid client secret is provided The client secret used for authentication is invalid or expired.t Generate a new client secret in the Azure portal and update the script with the new value. Ensure that the application registration is configured correctly and that all necessary API permissions are granted.

👥 Guest Accounts Are External by Nature

userType eq 'Guest' identifies accounts created for external collaboration. Disabling them cuts off access immediately but retains their account object for auditing or future reactivation.
📅 Filter Inactive Guest Users with Sign-In Data

Combine Get-MgUser with signInActivity/lastSignInDateTime to locate stale guest accounts. These are ideal candidates for being disabled or reviewed.

Conclusion

Managing guest user accounts is essential for maintaining security and ensuring that only authorized individuals have access to your organization’s resources. This script provides a straightforward way to disable guest user accounts using Microsoft Graph PowerShell. By implementing the suggested improvements, you can enhance the script’s functionality and make your account management process even more robust.

Regularly reviewing and managing guest user accounts helps to safeguard your organization’s data and maintain compliance with security policies. Try integrating this script into your workflow to streamline guest user management in your Microsoft 365 environment.


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