Thursday, 7 February 2019

Find Disabled Users in Office 365 Group using Powershell

In this post, I am going to share powershell script to find and list disabled users that are still a member of Office 365 Groups. In Azure AD environment, the disabled users are nothing but the sign-in access blocked users. You can retrieve Office 365 group members using the Exchange Online powershell command Get-UnifiedGroupLinks and find members' account status by using the Azure AD powershell command Get-AzureADUser. So we need to first connect both powershell modules before running the script.

First connect Exchange Online powershell module by running below commands:
$365Logon = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri -Credential $365Logon -Authentication Basic -AllowRedirection
Import-PSSession $Session
Run the below command to import AzureAD module:

Find and list disabled users who are still a member in a given Office 365 group:

#Replace your group name
$o365Group = "YourO365Group"
$groupMembers = Get-UnifiedGroupLinks -Identity $o365Group -LinkType Members -ResultSize Unlimited
$groupMembers | ForEach-Object {
$memberId = $_.ExternalDirectoryObjectId
$user = Get-AzureADUser -ObjectId $memberId -ErrorAction SilentlyContinue
If ($user -ne $Null) 
If ($user.AccountEnabled -eq $true) {
$userStatus = "Enabled"
} Else {
$userStatus = "Disabled"
$Result += New-Object PSObject -property @{ 
UserName = $user.DisplayName
UserPrincipalName = $user.UserPrincipalName
AccountStatus = $userStatus
#Write-Host "User not found: $_.DisplayName"
$Result |Where-Object {$_.AccountStatus -eq "Disabled"} | Select-Object UserName,UserPrincipalName

Export result to CSV file:

You can export disabled members of the given Office 365 Group to CSV file by running below command.
$Result | Where-Object {$_.AccountStatus -eq "Disabled"} |
Select-Object UserName,UserPrincipalName |
Export-CSV "C:\\DisabledO365GroupMembers.csv" -NoTypeInformation -Encoding UTF8

Find enabled users alone in Office 365 Group:

You can run the below command to list only enabled users that are member of the given O365 group.
$Result | Where-Object {$_.AccountStatus -eq "Enabled"} | Select-Object UserName,UserPrincipalName


No comments:

Post a Comment