We use cookies to improve your experience.
By your continued use of this site you accept such use.
For more details please see our privacy policy and cookies policy.

Script repository

Check group membership in Microsoft 365

October 05, 2023 Views: 1382

The script returns true if the target user is not a member of any of the specified groups in Microsoft 365. It should only be used in the If PowerShell script returns true condition. To execute the script, create a custom command, scheduled task or business rule configured for the User object type.

To use the script, install Microsoft.Graph on the computer where Adaxes service runs.

In the script, the $groupNames variable specifies names of the groups the user should not be a member of for the condition to be met.

Edit Remove
PowerShell
$groupNames = @("MyGroup1", "MyGroup2") # TODO: modify me
$Context.ConditionIsMet = $False

try
{
    # Get the object ID in Microsoft 365
    $objectId = ([Guid]$Context.TargetObject.Get("adm-O365ObjectId")).ToString()
}
catch
{
    $Context.LogMessage("The user doesn't have a Microsoft 365 account.", "Error")
    return
}

$token = ConvertTo-SecureString $Context.CloudServices.GetAzureAuthAccessToken() -AsPlainText -Force
Connect-MgGraph -AccessToken $token
foreach ($name in $groupNames)
{
    $group = Get-MgGroup -Filter "DisplayName eq '$name'"
    if ($NULL -eq $group)
    {
        $Context.LogMessage("Group with display name $name was not found. Group membership check cannot be completed.", "Error")
        return
    }
    
    $members = Get-MgGroupMember -GroupId $group.Id
    if ($members.Id -contains $objectId)
    {
        return
    }
}

$Context.ConditionIsMet = $True
Comments 0
Leave a comment
Loading...

Got questions?

Support Questions & Answers