Managing Guest Users with Graph PowerShell

Guest users are essential for collaboration in Microsoft 365, allowing external users to access necessary resources without adding them as full users in your directory. Managing these guest users is often time-consuming, but with Microsoft Graph PowerShell, you can streamline tasks like listing, creating, updating, and deleting guest users. This article introduces a robust, interactive PowerShell script that simplifies managing guest users directly from the console.

The Script

# Ensure Microsoft.Graph module is installed and imported
if (-not (Get-Module -ListAvailable -Name Microsoft.Graph)) {
    Install-Module -Name Microsoft.Graph -Scope CurrentUser -Force -AllowClobber
}
Import-Module Microsoft.Graph

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

function Show-Menu {
    Write-Host "`nChoose an action:"
    Write-Host "1. List all guest users"
    Write-Host "2. Create a new guest user"
    Write-Host "3. Update a guest user"
    Write-Host "4. Delete a guest user"
    Write-Host "5. Exit"
    return Read-Host "Enter your choice (1-5)"
}

function List-GuestUsers {
    try {
        $guests = Get-MgUser -Filter "userType eq 'Guest'" -All
        $guests | Format-Table DisplayName, UserPrincipalName, Mail, AccountEnabled -AutoSize
    } catch {
        Write-Host "Failed to retrieve guest users: $_" -ForegroundColor Red
    }
}

function Create-GuestUser {
    $displayName = Read-Host "Enter the guest's display name"
    $email = Read-Host "Enter the guest's email address"
    
    $params = @{
        displayName = $displayName
        mailNickname = $displayName -replace '\s', ''
        userPrincipalName = "$((New-Guid).Guid)@yourdomain.com"  # Use your domain here
        mail = $email
        userType = "Guest"
        externalUserState = "PendingAcceptance"
    }
    
    try {
        New-MgUser -BodyParameter $params
        Write-Host "Guest user created successfully."
    } catch {
        Write-Host "Failed to create guest user: $_" -ForegroundColor Red
    }
}

function Update-GuestUser {
    $userPrincipalName = Read-Host "Enter the UserPrincipalName of the guest user to update"
    $newDisplayName = Read-Host "Enter the new display name for the guest user"
    
    $params = @{
        displayName = $newDisplayName
    }
    
    try {
        Update-MgUser -UserId $userPrincipalName -BodyParameter $params
        Write-Host "Guest user updated successfully."
    } catch {
        Write-Host "Failed to update guest user: $_" -ForegroundColor Red
    }
}

function Delete-GuestUser {
    $userPrincipalName = Read-Host "Enter the UserPrincipalName of the guest user to delete"
    
    try {
        Remove-MgUser -UserId $userPrincipalName -Confirm:$false
        Write-Host "Guest user deleted successfully."
    } catch {
        Write-Host "Failed to delete guest user: $_" -ForegroundColor Red
    }
}

while ($true) {
    $choice = Show-Menu
    switch ($choice) {
        "1" { List-GuestUsers }
        "2" { Create-GuestUser }
        "3" { Update-GuestUser }
        "4" { Delete-GuestUser }
        "5" { 
            Write-Host "Exiting..."
            Disconnect-MgGraph
            break
        }
        default { Write-Host "Invalid choice. Please select a valid option." }
    }
}

See the Script in Action by clicking and playing this GIF:

How the Script Works

This script offers a user-friendly menu to select actions for managing guest users. Here’s a breakdown of each component:

  • Show-Menu: Displays the action menu for the administrator to choose the required operation.
  • List-GuestUsers: Lists all guest users by fetching users with userType eq 'Guest' using the Get-MgUser cmdlet.
  • Create-GuestUser: Creates a new guest user by generating a unique userPrincipalName and setting externalUserState to PendingAcceptance.
  • Update-GuestUser: Updates an existing guest user’s display name based on their UserPrincipalName.
  • Delete-GuestUser: Deletes a guest user based on their UserPrincipalName.
  • Exit Option: Ends the script and disconnects from Microsoft Graph.

Further Enhancements

  • Input Validation: Implement checks to ensure valid input, especially for email addresses and UserPrincipalName.
  • Error Logging: Add logging functionality to capture errors in a separate log file for troubleshooting.
  • Extended Attributes: Enable management of additional attributes such as Department or CompanyName.
  • Bulk Operations: Modify the script to handle bulk user actions via a CSV import.

Possible Errors & Solutions

Error Cause Solution
Insufficient Permissions The user running the script does not have the necessary permissions. Ensure the script is executed by a user with User.ReadWrite.All permissions in Microsoft Graph.
"The userPrincipalName format is invalid" The userPrincipalName format does not match your organization’s requirements. Customize the script to use a proper format for userPrincipalName as per organizational standards.
"User not found" on Update or Delete Incorrect UserPrincipalName provided. Use the List function to ensure the UserPrincipalName exists before attempting to update or delete.
Module Import Failure The Microsoft.Graph module is not installed or imported. Run Install-Module Microsoft.Graph to install the required module.

Conclusion

With this interactive Graph PowerShell script, you can manage guest users in Microsoft 365 quickly and efficiently. It saves time by providing an intuitive menu for administrators to perform essential tasks like listing, creating, updating, and deleting guest users without manual UI-based steps. Further enhancements and modifications can expand its usability, making it a scalable solution for managing external collaboration in your organization.

Suggested Reading

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