Office 365 Users' group membership report

Office 365 Users' group membership report
This commit is contained in:
AdminDroid 2023-04-25 20:07:33 +05:30
parent d3e95aa72c
commit da2995779e

View File

@ -2,64 +2,111 @@
============================================================================================= =============================================================================================
Name: Office365 User Membership Report Using PowerShell Name: Office365 User Membership Report Using PowerShell
Description: This script exports Office 365 user's group details to CSV Description: This script exports Office 365 user's group details to CSV
Version: 1.0 Version: 3.0
Website: o365reports.com Website: o365reports.com
Script by: O365Reports Team For detailed script execution:https://o365reports.com/2021/04/15/export-office-365-groups-a-user-is-member-of-using-powershell
For detailed script execution:https://o365reports.com/2021/04/15/export-office-365-groups-a-user-is-member-of-using-powershell/
============================================================================================ ============================================================================================
#> #>
param param
( (
[string] $UserName = $null,
[string] $Password = $null,
[String] $UsersIdentityFile, [String] $UsersIdentityFile,
[Switch] $GuestUsersOnly, [Switch] $GuestUsersOnly,
[Switch] $DisabledUsersOnly, [Switch] $DisabledUsersOnly,
[Switch] $UsersNotinAnyGroup [Switch] $UsersNotinAnyGroup,
[string] $TenantId,
[string] $ClientId,
[string] $CertificateThumbprint
) )
$MsGraphModule = Get-Module Microsoft.Graph -ListAvailable
if($MsGraphModule -eq $null)
{
Write-host "Important: Microsoft graph module is unavailable. It is mandatory to have this module installed in the system to run the script successfully."
$confirm = Read-Host Are you sure you want to install Microsoft graph module? [Y] Yes [N] No
if($confirm -match "[yY]")
{
Write-host "Installing Microsoft graph module..."
Install-Module Microsoft.Graph -Scope CurrentUser
Write-host "Microsoft graph module is installed in the machine successfully" -ForegroundColor Magenta
}
else
{
Write-host "Exiting. `nNote: Microsoft graph module must be available in your system to run the script" -ForegroundColor Red
Exit
}
}
if(($TenantId -ne "") -and ($ClientId -ne "") -and ($CertificateThumbprint -ne ""))
{
Connect-MgGraph -TenantId $TenantId -AppId $ClientId -CertificateThumbprint $CertificateThumbprint -ErrorAction SilentlyContinue -ErrorVariable ConnectionError|Out-Null
if($ConnectionError -ne $null)
{
Write-Host $ConnectionError -Foregroundcolor Red
Exit
}
}
else
{
Connect-MgGraph -Scopes "Directory.Read.All" -ErrorAction SilentlyContinue -Errorvariable ConnectionError |Out-Null
if($ConnectionError -ne $null)
{
Write-Host "$ConnectionError" -Foregroundcolor Red
Exit
}
}
Write-Host "Microsoft Graph Powershell module is connected successfully" -ForegroundColor Green
Select-MgProfile beta
Function UserDetails { Function UserDetails {
if ([string]$UsersIdentityFile -ne "") { if ([string]$UsersIdentityFile -ne "")
{
$IdentityList = Import-Csv -Header "UserIdentityValue" $UsersIdentityFile $IdentityList = Import-Csv -Header "UserIdentityValue" $UsersIdentityFile
foreach ($IdentityValue in $IdentityList) { foreach ($IdentityValue in $IdentityList)
{
$CurIdentity = $IdentityValue.UserIdentityValue $CurIdentity = $IdentityValue.UserIdentityValue
try { try
$LiveUser = Get-AzureADUser -ObjectId "$CurIdentity" -ErrorAction SilentlyContinue {
if ($GuestUsersOnly.IsPresent -and $LiveUser.UserType -ne "Guest") { $LiveUser = Get-MgUser -UserId "$CurIdentity" -ExpandProperty MemberOf -ErrorAction SilentlyContinue
if($GuestUsersOnly.IsPresent -and $LiveUser.UserType -ne "Guest")
{
continue continue
} }
if ($DisabledUsersOnly.IsPresent -and $LiveUser.AccountEnabled -eq $true) { if($DisabledUsersOnly.IsPresent -and $LiveUser.AccountEnabled -eq $true)
{
continue continue
} }
ProcessUser ProcessUser
} }
catch { catch
{
Write-Host Given UserIdentity: $CurIdentity is not valid/found. Write-Host Given UserIdentity: $CurIdentity is not valid/found.
} }
} }
} }
else { else
if ($GuestUsersOnly.Ispresent -and $DisabledUsersOnly.Ispresent) { {
Get-AzureADUser -Filter "UserType eq 'Guest'" | Where-Object { $_.AccountEnabled -eq $false } | ForEach-Object { if ($GuestUsersOnly.Ispresent -and $DisabledUsersOnly.Ispresent)
{
Get-MgUser -Filter "UserType eq 'Guest'" -ExpandProperty MemberOf -All| Where-Object { $_.AccountEnabled -eq $false } | ForEach-Object {
$LiveUser = $_ $LiveUser = $_
ProcessUser ProcessUser
} }
} }
elseif ($DisabledUsersOnly.Ispresent) { elseif ($DisabledUsersOnly.Ispresent)
Get-AzureADUser | Where-Object { $_.AccountEnabled -eq $false } | ForEach-Object { {
Get-MgUser -ExpandProperty MemberOf -All| Where-Object { $_.AccountEnabled -eq $false } | ForEach-Object {
$LiveUser = $_ $LiveUser = $_
ProcessUser ProcessUser
} }
} }
elseif ($GuestUsersOnly.Ispresent) { elseif ($GuestUsersOnly.Ispresent)
Get-AzureADUser -Filter "UserType eq 'Guest'" | ForEach-Object { {
Get-MgUser -Filter "UserType eq 'Guest'" -ExpandProperty MemberOf -All| ForEach-Object {
$LiveUser = $_ $LiveUser = $_
ProcessUser ProcessUser
} }
} }
else { else
Get-AzureADUser -All:$true | ForEach-Object { {
Get-MgUser -ExpandProperty MemberOf -All | ForEach-Object {
$LiveUser = $_ $LiveUser = $_
ProcessUser ProcessUser
} }
@ -68,108 +115,81 @@ Function UserDetails {
} }
Function ProcessUser { Function ProcessUser {
$GroupList = @() $GroupList = @()
$Roles = @() $RolesList = @()
$global:ProcessedUsers = $global:ProcessedUsers + 1 $Script:ProcessedUsers += 1
$UPN = $LiveUser.UserPrincipalName
$ObjectId = $LiveUser.ObjectId.ToString()
$Name = $LiveUser.DisplayName $Name = $LiveUser.DisplayName
Write-Progress -Activity "Processing $Name" -Status "Processed Users Count: $global:ProcessedUsers" Write-Progress -Activity "Processing $Name" -Status "Processed Users Count: $Script:ProcessedUsers"
$UserMembership = Get-AzureADUserMembership -ObjectId $ObjectId $UserMembership = Get-MgUserMemberOf -UserId $LiveUser.UserPrincipalName |Select-Object -ExpandProperty AdditionalProperties
$AllGroupData = $UserMembership | Where-object { $_.'@odata.type' -eq "#microsoft.graph.group" }
$AllGroupData = $UserMembership | Where-object { $_.ObjectType -eq "Group" } if ($AllGroupData -eq $null)
if ($null -eq $AllGroupData) { {
$GroupName = " - " $GroupName = " - "
} }
else { else
if ($UsersNotinAnyGroup.IsPresent) { {
if ($UsersNotinAnyGroup.IsPresent)
{
return return
} }
$AllGroupData | Select-Object DisplayName | ForEach-Object { $GroupName = (@($AllGroupData.displayName) -join ',')
$GroupList += $_.DisplayName -join ","
$GroupName = ($GroupList -join ",")
} }
} $AllRoles = $UserMembership | Where-object { $_.'@odata.type' -eq "#microsoft.graph.directoryRole" }
$AllRoles = $UserMembership | Where-object { $_.ObjectType -eq "Role" } | Select-Object DisplayName if ($AllRoles -eq $null) {
if ($null -eq $AllRoles) {
$RolesList = " - " $RolesList = " - "
} }
else { else
$AllRoles | ForEach-Object { {
$Roles += $_.DisplayName -join "," $RolesList = @($AllRoles.displayName) -join ','
$RolesList = ($Roles -join ",")
} }
} if ($LiveUser.AccountEnabled -eq $True)
if ($LiveUser.AccountEnabled -eq $True) { {
$AccountStatus = "Enabled" $AccountStatus = "Enabled"
} }
else { else
{
$AccountStatus = "Disabled" $AccountStatus = "Disabled"
} }
if ($null -eq $LiveUser.Department) { if ($LiveUser.Department -eq $null)
{
$Department = " - " $Department = " - "
} }
else { else
{
$Department = $LiveUser.Department $Department = $LiveUser.Department
} }
if ($LiveUser.AssignedLicenses -ne "") { if ($LiveUser.AssignedLicenses -ne "")
{
$LicenseStatus = "Licensed" $LicenseStatus = "Licensed"
} }
else { else
{
$LicenseStatus = "Unlicensed" $LicenseStatus = "Unlicensed"
} }
ExportResults ExportResults
} }
Function ExportResults { Function ExportResults {
$global:ExportedUsers = $global:ExportedUsers + 1 $Script:ExportedUsers += 1
$ExportResult = @{'Display Name' = $Name; 'Email Address' = $UPN; 'Group Name(s)' = $GroupName; 'License Status' = $LicenseStatus; 'Account Status' = $AccountStatus;'Department' = $Department;'Admin Roles' = $RolesList } $ExportResult = [PSCustomObject] @{'Display Name' = $Name; 'Email Address' = $LiveUser.UserPrincipalName; 'Group Name(s)' = $GroupName; 'License Status' = $LicenseStatus; 'Account Status' = $AccountStatus;'Department' = $Department;'Admin Roles' = $RolesList }
$ExportResults = New-Object PSObject -Property $ExportResult $ExportResult | Export-csv -path $ExportCSVFileName -NoType -Append
$ExportResults | Select-Object 'Display Name', 'Email Address', 'Group Name(s)', 'License Status', 'Account Status', 'Department', 'Admin Roles' | Export-csv -path $ExportCSVFileName -NoType -Append
} }
Function Connection { $ProcessedUsers = 0
$AzureAd = (Get-Module AzureAD -ListAvailable).Name $ExportedUsers = 0
if ($Empty -eq $AzureAd) {
Write-host "Mandatory module is unavailable: Install AzureAd module to run the script successfully. Please choose (Y or y) to say Yes"
$confirm = Read-Host Are you sure you want to install module? [Y] Yes [N] No
if ($confirm -match "[yY]") {
Write-host "Installing AzureAD"
Install-Module AzureAd -Allowclobber -Repository PSGallery -Force
Write-host "Required Module is installed in the machine Successfully"
}
else {
Write-host "Exiting. `nNote:The Module AzureAD must be available in your system to run the script"
Exit
}
}
#Importing Module by default will avoid the cmdlet unrecognized error
Import-Module AzureAd -ErrorAction SilentlyContinue -Force
Write-Host "Connecting to AzureAD..."
#Storing credential in script for scheduling purpose/Passing credential as parameter
if (($UserName -ne "") -and ($Password -ne "")) {
$SecuredPassword = ConvertTo-SecureString -AsPlainText $Password -Force
$Credential = New-Object System.Management.Automation.PSCredential $UserName, $SecuredPassword
Connect-AzureAD -Credential $Credential | Out-Null
}
else {
Connect-AzureAD | Out-Null
}
}
Connection
$global:ProcessedUsers = 0
$global:ExportedUsers = 0
$ExportCSVFileName = ".\UserMembershipReport_$((Get-Date -format MMM-dd` hh-mm-ss` tt).ToString()).csv" $ExportCSVFileName = ".\UserMembershipReport_$((Get-Date -format MMM-dd` hh-mm-ss` tt).ToString()).csv"
UserDetails UserDetails
#Open output file after execution #Open output file after execution
if ((Test-Path -Path $ExportCSVFileName) -eq "True") { if ((Test-Path -Path $ExportCSVFileName) -eq "True") {
Write-Progress -Activity "--" -Completed Write-Progress -Activity "--" -Completed
Write-Host "The Output result has $global:ExportedUsers users details" Write-Host "`nThe Output result has " -NoNewline
Write-Host $Script:ExportedUsers Users -ForegroundColor Magenta -NoNewline
Write-Host " details"
Write-Host `nThe Output file available in $ExportCSVFileName -ForegroundColor Green Write-Host `nThe Output file available in $ExportCSVFileName -ForegroundColor Green
$prompt = New-Object -ComObject wscript.shell $prompt = New-Object -ComObject wscript.shell
$userInput = $prompt.popup("Do you want to open output file?", 0, "Open Output File", 4) $userInput = $prompt.popup("Do you want to open output file?", 0, "Open Output File", 4)
If ($userInput -eq 6) { if ($userInput -eq 6) {
Invoke-Item "$ExportCSVFileName" Invoke-Item "$ExportCSVFileName"
} }
} }
else { else
Write-Host `nNo data/user found with the specified criteria {
Write-Host `nNo data/user found with the specified criteria -ForegroundColor Red
} }