Script Repository


Disable Microsoft 365 services for user

April 28, 2020
1384

The script disables specific Microsoft 365 (Office 365) services for a user no matter which license plan they belong to.

For the script to work, you need to install Microsoft Azure Active Directory Module for Windows PowerShell on each computer where Adaxes service is running.

Parameter

Edit Remove
PowerShell
$servicePlansToDisable = @("YAMMER_ENTERPRISE", "PROJECTWORKMANAGEMENT", "SWAY") # TODO: modify me

# Get Microsoft 365 Object ID
try
{
    $objectId = [Guid]$Context.TargetObject.Get("adm-O365ObjectId")
}
catch
{
    return # No Microsoft 365 account
}

# Get credentials of the Microsoft 365 tenant associated with the user
$microsoft365Cred = $Context.GetOffice365Credential()

$scriptBlock = {
    param($microsoft365Cred, $objectId, $servicePlansToDisable)
    Import-Module MsOnline
    
    # Connect to Microsoft 365
    Connect-MsolService -Credential $microsoft365Cred
    
    # Get licenses assigned to user
    $user = Get-MsolUser -ObjectId $objectId
    
    foreach ($license in $user.Licenses)
    {
        $serviceStatus = $license.ServiceStatus

        # Decide whether it is necessary to disable any services
        $disabledServices = @()
        foreach ($servicePlan in $license.ServiceStatus)
        {
            if (($servicePlansToDisable -notcontains $servicePlan.ServicePlan.ServiceName) -and ($servicePlan.ProvisioningStatus -ne 'Disabled') -and ($servicePlan.ProvisioningStatus -ne 'None'))
            {
                continue
            }
    
            $disabledServices += $servicePlan.ServicePlan.ServiceName
        }
    
        if ($disabledServices.Length -eq 0)
        {
            continue
        }
        
        # Disable the services
        $licenseOptions = New-MsolLicenseOptions –AccountSkuId $license.AccountSkuId –DisabledPlans $disabledServices
        Set-MsolUserLicense -ObjectId $objectId -LicenseOptions $licenseOptions
    }
}

try
{
    # Execute the script in a separate PowerShell instance to avoid Microsoft 365 authentication within Adaxes thread
    Invoke-Command -ScriptBlock $scriptBlock -ArgumentList $microsoft365Cred, $objectId.ToString(), $servicePlansToDisable -ComputerName localhost -ErrorAction Stop
}
catch
{
    $Context.LogMessage("An error occurred when disabling Microsoft 365 services for the user. Error: " + $_.Exception.Message, "Warning")
}


Comments ( 0 )
No results found.
Leave a comment