Script Repository


Set manager of user as owner of Microsoft 365 groups owned by the user

April 12, 2021
738

The script finds Microsoft 365 (Office 365) groups for which the target user is set as owner and sets the user manager as the groups owner. To run the script, create a custom command, business rule or scheduled task configured for the User object type.

Distribution and mail-enabled security groups

Edit Remove
PowerShell
# Get the user's unique identifier in Microsoft 365
try
{
    $objectId = ([Guid]$Context.TargetObject.Get("adm-O365ObjectId")).ToString()
}
catch
{
    $Context.LogMessage("The user %fullname% does not have an account in Microsoft 365.", "Warning")
    return
}

# Get user manager
try
{
    $managerDN = $Context.TargetObject.Get("manager")
}
catch
{
    $Context.LogMessage("The user %fullname% does not have a manager specified.", "Error")
    return
}

# Get manager's unique identifier in Microsoft 365
try
{
    $manager = $Context.BindToObjectByDN($managerDN)
    $managerId = ([Guid]$manager.Get("adm-O365ObjectId")).ToString()
}
catch
{
    $Context.LogMessage("Manager of user %fullname% does not have an account in Microsoft 365.", "Error")
    return
}

try
{
    # Connect to Exchange Online
    $session = $Context.CloudServices.CreateExchangeOnlinePSSession()
    Import-PSSession $session -AllowClobber -DisableNameChecking -CommandName "Get-User", "Get-Recipient", "Set-DistributionGroup"

    # Get user DN
    $user = Get-User $objectId
    $userDN = $user.DistinguishedName
    
    # Get all security mail-enabled and distribution groups the target user is currently owner of
    $groups = Get-Recipient -Filter "ManagedBy -eq '$userDN'" -RecipientTypeDetails "MailUniversalDistributionGroup","MailUniversalSecurityGroup"
    foreach ($group in $groups)
    {
        try
        {
            Set-DistributionGroup -Identity $group.ExternalDirectoryObjectId -ManagedBy @{Add=$managerId;Remove=$objectId} -Confirm:$False -ErrorAction Stop
        }
        catch
        {
            $Context.LogMessage("An error occurred when updating the owner of the $($group.DisplayName) group. Error message: " + $_.Exception.Message, "Warning")
            continue
        }
    }
}
finally
{
    # Close the remote session and release resources
    if ($session) { Remove-PSSession $session }
}

Security groups that are not mail-enabled and unified groups

To use the script, install the AzureAD module on the computer where Adaxes service is running.

Edit Remove
PowerShell
# Get the user's unique identifier in Microsoft 365
try
{
    $objectId = ([Guid]$Context.TargetObject.Get("adm-O365ObjectId")).ToString()
}
catch
{
    $Context.LogMessage("The user %fullname% does not have an account in Microsoft 365.", "Warning")
    return
}

# Get user manager
try
{
    $managerDN = $Context.TargetObject.Get("manager")
}
catch
{
    $Context.LogMessage("The user %fullname% does not have a manager specified.", "Error")
    return
}

# Get manager's unique identifier in Microsoft 365
try
{
    $manager = $Context.BindToObjectByDN($managerDN)
    $managerId = ([Guid]$manager.Get("adm-O365ObjectId")).ToString()
}
catch
{
    $Context.LogMessage("Manager of user %fullname% does not have an account in Microsoft 365.", "Error")
    return
}

# Connect to AzureAD
$token = $Context.CloudServices.GetAzureAuthAccessToken("https://graph.windows.net/")
$tenant = $Context.CloudServices.GetO365Tenant()
$credential = $tenant.GetCredential()
Connect-AzureAD -AccountId $credential.AppId -AadAccessToken $token -TenantId $tenant.TenantId

# Get all objects the target user is owner of
$objects = Get-AzureADUserOwnedObject -ObjectId $objectId -All:$true

# Update group owners
foreach ($object in $objects)
{
    if ($object.ObjectType -ne "Group")
    {
        continue
    }
    
    try
    {
        Add-AzureADGroupOwner -ObjectId $object.ObjectId -RefObjectId $managerId
    }
    catch
    {
        $Context.LogMessage("An error occurred when adding manager of user to the $($object.DisplayName) group as the owner. Error message: " + $_.Exception.Message, "Warning")
        continue
    }
    
    try
    {
        Remove-AzureADGroupOwner -ObjectId $object.ObjectId -OwnerId $objectId
    }
    catch
    {
        $Context.LogMessage("An error occurred when removing the user as owner of the $($object.DisplayName) group. Error message: " + $_.Exception.Message, "Warning")
        continue
    }
}

Comments ( 4 )
avatar
Dylan
Mar 29, 2021
For the first script "Distribution and mail-enabled Security Groups" I get this error message.

You cannot call a method on a null-valued expression. Stack trace: at <ScriptBlock>, <No file>: line 38

Is there any reason for this?
avatar
Support
Mar 30, 2021
Hello Dylan,

It looks like you are running the script in Adaxes 2020.1 or older where the $Context.CloudServices.CreateExchangeOnlinePSSession() method is not available. For information on how to check your version, have a look at the following help article: https://www.adaxes.com/help/CheckServiceVersion.

If your version of Adaxes is older than Adaxes 2021.1, you can use the below script to update distribution and mail-enabled security groups in Microsoft 365.
Edit Remove
PowerShell
# Get the user's unique identifier in Microsoft 365
try
{
    $objectId = ([Guid]$Context.TargetObject.Get("adm-O365ObjectId")).ToString()
}
catch
{
    $Context.LogMessage("The user %fullname% does not have an account in Microsoft 365.", "Warning")
    return
}

# Get user manager
try
{
    $managerDN = $Context.TargetObject.Get("manager")
}
catch
{
    $Context.LogMessage("The user %fullname% does not have a manager specified.", "Error")
    return
}

# Get manager's unique identifier in Microsoft 365
try
{
    $manager = $Context.BindToObjectByDN($managerDN)
    $managerId = ([Guid]$manager.Get("adm-O365ObjectId")).ToString()
}
catch
{
    $Context.LogMessage("Manager of user %fullname% does not have an account in Microsoft 365.", "Error")
    return
}

try
{
    # Connect to Exchange Online
    Connect-ExchangeOnline -Credential $Context.GetOffice365Credential()

    # Get user DN
    $user = Get-User $objectId
    $userDN = $user.DistinguishedName
    
    # Get all security mail-enabled and distribution groups the target user is currently owner of
    $groups = Get-Recipient -Filter "ManagedBy -eq '$userDN'" -RecipientTypeDetails "MailUniversalDistributionGroup","MailUniversalSecurityGroup"
    foreach ($group in $groups)
    {
        try
        {
            Set-DistributionGroup -Identity $group.ExternalDirectoryObjectId -ManagedBy @{Add=$managerId;Remove=$objectId} -Confirm:$False -ErrorAction Stop
        }
        catch
        {
            $Context.LogMessage("An error occurred when updating the owner of the $($group.DisplayName) group. Error message: " + $_.Exception.Message, "Warning")
            continue
        }
    }
}
finally
{
    # Close the remote session and release resources
    if ($session) { Remove-PSSession $session }
}
avatar
David Blodgett
Apr 09, 2021
In the second script for non-mail-enabled security and unified groups there is a problem with the log messages. The foreach loop sets the object variable name as $object, but the log message lines reference $group.DisplayName. Changing these lines to $object.DisplayName resolves the issue.
avatar
Support
Apr 12, 2021
Hello David,

Thank you for pointing out the issue. We have updated the script as you suggested.
Leave a comment