How to obtain list of guest users with "pending acceptance" status while excluding guest users in 2 that are members of 2 other groups in AzureAD

Anonymous
2023-07-10T08:40:10.56+00:00

Hi,

We need to do a bit of clean-up of guest users who are in "Pending Acceptance" state for more than 6 months. At the same time, we need to exclude accounts that are synced from other tenants from the clean-up. These synced accounts are isolated in 2 groups.

Right now, I am able to export all guest users with the following query

$AzureUsers = Get-AzureAdUser -All $true -Filter "usertype eq 'guest'" | Where-Object -Property Userstate -EQ -Value 'PendingAcceptance'
$AzureUsers | ForEach-Object {
    $ADUserExtension = (Get-AzureADUserExtension -ObjectId $_.ObjectId).Get_Item("createdDateTime")
    [PSCustomObject]@{
        UserPrincipalName = $_.UserPrincipalName
        Objectid          = $_.Objectid 
        UserState         = $_.UserState
        UserType          = $_.UserType
        Mail              = $_.Mail
        CreatedDateTime   = $ADUserExtension
    }
} | 
Export-Csv -Path C:\Temp\DeletedGUsers19.csv -NoTypeInformation

I need to exclude guest users that are members of 2 Azure AD groups. I don't know how to do that.

Thank you.

Femi

Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
22,990 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Vasil Michev 112.1K Reputation points MVP
    2023-07-10T17:33:30.9933333+00:00

    You should switch to using the Graph SDK for PowerShell, as the Azure AD module is not receiving any updates. You should also use server-side filters where appropriate, in this case you can do something like this:

    Select-MgProfile beta
    $users = Get-MgUser -Filter "userType eq 'Guest' and externalUserState eq 'PendingAcceptance'" -All -ExpandProperty memberOf
    $users | ? {!($_.MemberOf.Id -match 'c91cd116-a8a5-443b-9ae1-e1f0bade4a23|528a4052-fa6c-4495-b39f-2820f8e1e8db')}
    

    where you have to provide the GUIDs of the groups you want to exclude.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.