Managing Guest Users in Azure Active Directory with PowerShell – A Game Changer for IT Admins!

Are you tired of manually managing guest users in your Azure Active Directory (Azure AD)? Well, have no fear because with the power of PowerShell, we can automate this process and make it a breeze!

The script we’ll be discussing in this post uses the AzureAD PowerShell module to connect to Azure AD and retrieve guest users who have not accepted an invitation within 45 days or who have not logged in within 180 days. And get this – it then automatically removes those users from the organization!

No more manual labor, no more wasted time, and no more headaches – just pure efficiency and organization.

Here’s the script in its entirety, ready to revolutionize your guest user management.

<#
    .NOTES
    ===========================================================================
     Organization:  HDSupply
     Filename:      RB-AZ-RemovePendingGuest.ps1
     ScheduleFrequency: Weekly
    ===========================================================================
    .SYNOPSIS
    This script connects to Azure Active Directory, and then removes all guest users whose state is "PendingAcceptance" and whose refresh tokens were last valid 45 days ago or earlier, and all guest users whose state is "Accepted" and whose refresh tokens were last valid 180 days ago or earlier.
    .DESCRIPTION
    This script uses the AzureAD PowerShell module to connect to Azure AD and retrieve guest users who have not accepted an invitation within 45 days or who have not logged in within 180 days. The script then removes those users from the organization.
    This script is intended to be run on a schedule (e.g. Weekly) to keep the list of guest users in the organization up-to-date. It uses the "CloudAdmin" credentials to connect to Azure AD, which should be configured in the Automation service prior to running the script.
#>

# Variables to get Connected!
[PSCredential]$creds = Get-AutomationPSCredential -Name "ClientSecret"
[PSCredential]$cred = Get-AutomationPSCredential -Name "CloudAdmin"
[string]$clientID = $creds.UserName
[string]$clientSecret = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($creds.Password))
[string]$tenantName = "Enter TenantID or your TenantName"
[hashtable]$reqTokenBody = @{
    Grant_Type    = "client_credentials"
    Scope         = "https://graph.microsoft.com/.default"
    client_Id     = $clientID
    Client_Secret = $clientSecret
}
[string]$TokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token" -Method POST -Body $ReqTokenBody
[string]$TokenResponse | ConvertTo-Json
[string]$Token = $TokenResponse.access_token\

#Import Modules and Connect
Import-Module Microsoft.Graph.Users
Import-module AzureAD
Select-MgProfile -Name "beta"
Connect-MgGraph -AccessToken $Token
Connect-AzureAD -Credential $cred

# This line retrieves all guest users whose state is "PendingAcceptance" and whose refresh tokens were last valid 45 days ago or earlier
[Array]$PendingUsers = Get-AzureADUser -Filter "UserType eq 'Guest' and UserState eq 'PendingAcceptance'" -all $true | where { $_.RefreshTokensValidFromDateTime -lt (Get-Date).AddDays(-45) }
foreach ($PendingUser in $PendingUsers)
{
    # This line assigns the object ID of the current user to a variable
    $PendingUserObjectID = $PendingUser.ObjectId
    # This line outputs a message indicating that the user is being removed
    Write-Output "Removing Pending User $($PendingUser.DisplayName)"
    # This line removes the user using their object ID
    Remove-AzureADUser -ObjectId $PendingUserObjectID
}

#Days
[int]$days = 180

# This line retrieves all guest users whose state is "Accepted"
[Array]$AcceptedUsers = Get-AzureADUser -Filter "UserType eq 'Guest' and UserState eq 'Accepted'" -all $true
Foreach ($acceptedUser in $acceptedUsers)
{
    # This line assigns the object ID of the current user to a variable
    [string]$acceptedUserObjectID = $acceptedUser.ObjectId
    # Get the last sign-in date for the guest
    [Nullable[datetime]]$lastSignInDate = (Get-MgUser -UserId $acceptedUserObjectID -Property 'SigninActivity').signinactivity.LastSignInDateTime
    If ($Null -eq $lastSignInDate -or $lastSignInDate -eq '01/01/0001 00:00:00')
    {
        # Get the Date they Accepted the invitation since they never signed in. 
        $lastSignInDate = $AcceptedUser.RefreshTokensValidFromDateTime
    }
    # Calculate the number of days since the last sign-in
    [int]$daysSinceLastSignIn = (New-TimeSpan -Start $lastSignInDate -End (Get-Date)).Days
    # Check if the guest hasn't signed in for the specified number of days
    if ($daysSinceLastSignIn -ge $days)
    {
        # Output a message indicating that the user is being removed
        Write-Output "Removing user $($acceptedUser.DisplayName) who hasn't signed in for $daysSinceLastSignIn  days"
        # Remove the user
        Remove-AzureADUser -ObjectId $acceptedUserObjectID
    }
    $Null = $lastSignInDate
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s