Forum Discussion

fstorer's avatar
fstorer
Brass Contributor
Jun 01, 2022
Solved

Exclude test guest users from a script listing all guest users

Dear All, I am trying to find a quick way to exclude all our "test" guest users from a powershell script which lists all the guest users in our tenant. The script is quite simple:   $GuestUsers =...
  • LainRobertson's avatar
    LainRobertson
    Jun 02, 2022

    fstorer

     

    Hey, Francesco.

     

    Yeah, there's multiple ways to tackle this both in the server-side (which would be rather ugly) and client-side filtering contexts.

     

    If there's anything common about the test accounts, perhaps a client-side Regex approach would be easiest, as that would automatically identify any new test accounts added later on.

     

    Here's an example of the client-side Regex approach, which I've tacked onto the "getting" side:

    $GuestUsers = Get-AzureADUser -Filter "UserType eq 'Guest'" -All $true | Where-Object { $_.displayName -notmatch "test|someOtherName|yetAnotherName" } | Select-Object DisplayName,JobTitle,Mail,UserType,AccountEnabled | Sort-Object DisplayName

     

    Basically, you're just added values to exclude separated by the pipe ("|") symbol.

     

    If you want to go down the array path, this is one approach you could take. The notable difference in my example is that only exact matches would be excluded.

     

    You could blend the two but for 15 or so accounts, it's not worth doing so.

    $Exclusions = @(
        "test1",
        "test2",
        "test3"
    )
    
    $GuestUsers = Get-AzureADUser -Filter "UserType eq 'Guest'" -All $true | Where-Object { $_.displayName -notin $Exclusions } | Select-Object DisplayName,JobTitle,Mail,UserType,AccountEnabled | Sort-Object DisplayName

     

    Cheers,

    Lain

Resources