Manage Microsoft 365 Users with Graph PowerShell

Managing Microsoft 365 users is a routine task for administrators, involving various operations such as retrieving user details, adding new users, updating user information, removing users, managing licenses, and enabling/disabling user accounts. Automating these processes using Microsoft Graph PowerShell can greatly simplify user management and improve efficiency.

In this article, we present an interactive Graph PowerShell script that allows administrators to manage Microsoft 365 users efficiently. The script covers essential tasks, including assigning and removing licenses, updating user accounts, and more, all while ensuring proper error handling and a user-friendly experience.

The Script:


    # Connect to Microsoft Graph with the necessary scopes
    Connect-MgGraph -Scopes "User.ReadWrite.All", "Directory.ReadWrite.All"

    # Function to display menu options and get user input
    function Show-Menu {
        Write-Host "====================================="
        Write-Host "  Microsoft 365 User Management Menu  "
        Write-Host "====================================="
        Write-Host "1. Retrieve User Details"
        Write-Host "2. Add a New User"
        Write-Host "3. Update an Existing User"
        Write-Host "4. Remove a User"
        Write-Host "5. Enable/Disable User Account"
        Write-Host "6. Assign or Remove License"
        Write-Host "7. Exit"
        Write-Host "====================================="
        $choice = Read-Host "Please select an action (1-7)"
        return $choice
    }

    # Function to retrieve user details
    function Retrieve-UserDetails {
        $users = Get-MgUser -All -Filter "accountEnabled eq true" -Property Id, DisplayName, UserPrincipalName, AccountEnabled
        $users | ForEach-Object {
        Write-Host "ID: $($_.Id), Name: $($_.DisplayName), UPN: $($_.UserPrincipalName), AccountEnabled: $($_.AccountEnabled)"
      }
    }

    # Function to add a new user
    function Add-NewUser {
        $displayName = Read-Host "Enter Display Name"
        $upn = Read-Host "Enter UserPrincipalName (email)"
        $mailNickname = Read-Host "Enter Mail Nickname"
        $password = Read-Host "Enter Initial Password"

    $newUserParams = @{
        "DisplayName" = $displayName
        "UserPrincipalName" = $upn
        "MailNickname" = $mailNickname
        "AccountEnabled" = $true
        "PasswordProfile" = @{
        "Password" = $password
        "ForceChangePasswordNextSignIn" = $true
        }
    }

    Write-Host "Creating new user..."
    New-MgUser -BodyParameter $newUserParams
    Write-Host "New user created successfully."
   }

    # Function to update an existing user
    function Update-User {
        $upn = Read-Host "Enter UserPrincipalName of the user to update"
        $displayName = Read-Host "Enter new Display Name"
        $mailNickname = Read-Host "Enter new Mail Nickname"

        $updatedUserParams = @{
        "DisplayName" = $displayName
        "MailNickname" = $mailNickname
        }

        Write-Host "Updating user $upn..."
        Update-MgUser -UserId $upn -BodyParameter $updatedUserParams
        Write-Host "User updated successfully."
    }

    # Function to remove a user
    function Remove-User {
    $upn = Read-Host "Enter UserPrincipalName of the user to remove"
    try {
        # Get user and check if they exist
        $targetUser = Get-MgUser -UserId $upn
        if ($null -ne $targetUser) {
        # Remove the user
        Write-Host "Removing user $upn..."
        Remove-MgUser -UserId $targetUser.Id -Confirm:$false
        Write-Host "User $upn removed successfully."
        } else {
        Write-Host "User $upn not found."
        }
    } catch {
        Write-Host "Error: $_"
    }
    }

    # Function to enable or disable a user account using -BodyParameter
    function EnableDisable-UserAccount {
    $upn = Read-Host "Enter UserPrincipalName of the user"
        try {
            $targetUser = Get-MgUser -UserId $upn -Property AccountEnabled
            if ($targetUser.AccountEnabled -eq $true) {
            Write-Host "Disabling account for $upn..."
            $disableParams = @{
            "AccountEnabled" = $false
            }
            Update-MgUser -UserId $upn -BodyParameter $disableParams
            Write-Host "Account disabled."
        } else {
            Write-Host "Enabling account for $upn..."
            $enableParams = @{
            "AccountEnabled" = $true
            }
            Update-MgUser -UserId $upn -BodyParameter $enableParams
            Write-Host "Account enabled."
        }
        } catch {
            Write-Host "Error: $_"
        }
    }

    # Function to assign or remove a license (updated)
    function AssignRemove-License {
    $upn = Read-Host "Enter UserPrincipalName of the user"
    $licenseSku = Read-Host "Enter License SKU to assign (e.g., ENTERPRISEPACK for Office 365 E3)"

    try {
        # Retrieve user and ensure they exist
        $user = Get-MgUser -UserId $upn

        if ($null -eq $user) {
        Write-Host "User not found."
        return
        }

        # Retrieve the license SKU ID for the given SKU
        $license = Get-MgSubscribedSku | Where-Object { $_.SkuPartNumber -eq $licenseSku }

        if ($null -eq $license) {
        Write-Host "License SKU not found."
        return
        }

        $licenseSkuId = $license.SkuId

        # Retrieve current assigned licenses
        $assignedLicenses = Get-MgUserLicenseDetail -UserId $upn
        $licenseExists = $assignedLicenses.AssignedPlans.SkuId -contains $licenseSkuId

        if (-not $licenseExists) {
        Write-Host "Assigning license $licenseSku to user $upn..."
        # Ensure both -AddLicenses and -RemoveLicenses are included in the command
        Set-MgUserLicense -UserId $upn -AddLicenses @{SkuId = $licenseSkuId} -RemoveLicenses @{}
        Write-Host "License assigned."
        } else {
        Write-Host "License $licenseSku is already assigned to user."
        }
    } catch {
        Write-Host "Error: $_"
        }
    }

    # Main program loop
    do {
    $choice = Show-Menu
    switch ($choice) {
        1 { Retrieve-UserDetails }
        2 { Add-NewUser }
        3 { Update-User }
        4 { Remove-User }
        5 { EnableDisable-UserAccount }
        6 { AssignRemove-License }
        7 { Write-Host "Exiting..."; break }
        default { Write-Host "Invalid choice, please try again." }
    }
    } while ($choice -ne 7)

    # Disconnect session
    Disconnect-MgGraph


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

How the Script Works

This script provides an interactive way for administrators to manage Microsoft 365 Groups. Here's how each function works:

  • Menu and User Input: The script starts by displaying a menu where the administrator selects the desired action (e.g., retrieving user details, adding a new user, etc.).
  • Retrieve User Details: The script retrieves all active users and displays their details such as ID, display name, user principal name (UPN), and account status.
  • Add a New User: The script prompts the administrator to input the display name, UPN, mail nickname, and initial password for a new user. It then creates the new user with these details.
  • Update a User: This section allows the administrator to update the display name and mail nickname of an existing user based on their UPN.
  • Remove a User: The script checks if a user exists based on the entered UPN, and if found, the user is removed from Microsoft 365.
  • Enable/Disable User Account: The script toggles the AccountEnabled status for a user. It uses the -BodyParameter hashtable to properly pass the AccountEnabled property.
  • Assign or Remove a License: : The script assigns or checks if a license is already assigned. It handles the license assignment by passing the appropriate SkuId and ensuring the -RemoveLicenses @{} parameter is included.
  • Loop and Exit: After performing an action, the script returns to the main menu until the user chooses to exit.

Further Enhancements

There are several ways to further enhance this script for more robust Microsoft 365 User management:

  • Bulk Operations: Modify the script to perform bulk operations using a CSV file, such as adding or updating multiple users or licenses at once.
  • Additional User Attributes: Expand the update function to allow more fields such as job title, department, and manager details to be updated.
  • Advanced License Management: Enhance the license management section to allow for bulk license assignment or removal, or include dynamic license queries for better license tracking.

Possible Errors & Solutions

  • Error: Set-MgUserLicense Cannot convert the literal 'System.Collections.Hashtable' to the expected type 'Edm.Guid'.
    • Cause: Incorrect handling of the SkuId as a hashtable.
    • Solution: Ensure that SkuId is retrieved and passed as a GUID using Get-MgSubscribedSku.
  • Error: User not found: User not found.
    • Cause: UPN entered incorrectly or user does not exist.
    • Solution: Verify the UPN and ensure the user exists in the directory before attempting operations.
  • Error: AccountEnabled: cannot be passed directly.
    • Cause: AccountEnabled must be passed within a -BodyParameter hashtable.
    • Solution: Use the -BodyParameter option when enabling or disabling accounts, as shown in the script.

Conclusion

This interactive Graph PowerShell script is a comprehensive solution for administrators to manage Microsoft 365 users with ease. By automating tasks like adding users, updating user details, managing licenses, and enabling/disabling accounts, administrators can save time and reduce the risk of manual errors. With further enhancements, this script can be expanded to meet more advanced user management needs.

Suggested Reading

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