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.
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
The script works as follows:
try {
# Code to fetch sign-in activities
} catch {
Write-Host "An error occurred: $_"
}
# 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."
}
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.
© m365corner.com. All Rights Reserved. Design by HTML Codex