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

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.

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