Advertisement
D0cEvil

ActiveDirectory - Distribution Group Membership

Dec 6th, 2022
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PowerShell 8.61 KB | Cybersecurity | 0 0
  1. Param
  2. (
  3.     [Parameter(Mandatory = $false)]
  4.     [string]$GroupNamesFile,
  5.     [switch]$IsEmpty,
  6.     [int]$MinGroupMembersCount,
  7.     [switch]$MFA,
  8.     [Nullable[boolean]]$ExternalSendersBlocked = $null,
  9.     [string]$UserName,
  10.     [string]$Password
  11. )
  12.  
  13. Function Get_members
  14. {
  15.  $DisplayName=$_.DisplayName
  16.  Write-Progress -Activity "`n     Processed Group count: $Count "`n"  Getting members of: $DisplayName"
  17.  $Alias=$_.Alias
  18.  $EmailAddress=$_.PrimarySmtpAddress
  19.  $GroupType=$_.GroupType
  20.  $ManagedBy=$_.ManagedBy
  21.  $ExternalSendersAllowed=$_.RequireSenderAuthenticationEnabled
  22.  if(($ExternalSendersBlocked -ne $null) -and ($ExternalSendersBlocked -ne $ExternalSendersAllowed))
  23.  {
  24.   $Print=0
  25.  }
  26.  #Get Distribution Group Authorized Senders
  27.  $AcceptMessagesOnlyFrom=$_.AcceptMessagesOnlyFromSendersOrMembers
  28.  $AuthorizedSenders=""
  29.  if($AcceptMessagesOnlyFrom.Count -gt 0)
  30.  {
  31.   foreach($item in $AcceptMessagesOnlyFrom)
  32.   {
  33.    $AuthorizedSenders=$AuthorizedSenders+$item
  34.    if($AcceptMessagesOnlyFrom.indexof($item) -lt (($AcceptMessagesOnlyFrom.count)-1))
  35.    {
  36.     $AuthorizedSenders=$AuthorizedSenders+","
  37.    }
  38.   }
  39.  }
  40.  elseif($ExternalSendersAllowed -eq "True")
  41.  {
  42.   $AuthorizedSenders="Only Senders in Your Organization"
  43.  }
  44.  else
  45.  {
  46.   $AuthorizedSenders="Senders inside & Outside of Your Organization"
  47.  }
  48.  
  49.  $Manager=""
  50.  if($_.ManagedBy.Count -gt 0)
  51.  {
  52.   foreach($ManageBy in $ManagedBy)
  53.   {
  54.    $Manager=$Manager+$ManageBy
  55.    if($ManagedBy.indexof($ManageBy) -lt (($ManagedBy.count)-1))
  56.    {
  57.     $Manager=$Manager+","
  58.    }
  59.   }
  60.  }
  61.  $Recipient=""
  62.  $RecipientHash=@{}
  63.  for($KeyIndex = 0; $KeyIndex -lt $RecipientTypeArray.Length; $KeyIndex += 2)
  64.  {
  65.   $key=$RecipientTypeArray[$KeyIndex]
  66.   $Value=$RecipientTypeArray[$KeyIndex+1]
  67.   $RecipientHash.Add($key,$Value)
  68.  }
  69.  $Members=Get-DistributionGroupMember -ResultSize Unlimited -Identity $DisplayName
  70.  $MembersCount=($Members.name).Count
  71.  
  72.  #GroupSize Filter
  73.  if(([int]$MinGroupMembersCount -ne "") -and ($MembersCount -lt [int]$MinGroupMembersCount))
  74.  {
  75.   $Print=0
  76.  }
  77.  
  78.  #Check for Empty Group
  79.  elseif($MembersCount -eq 0)
  80.  {
  81.   $Member="No Members"
  82.   $MemberEmail="-"
  83.   $RecipientTypeDetail="-"
  84.   Print_Output
  85.  }
  86.  
  87.  #Loop through each member in a group
  88.  else
  89.  {
  90.   foreach($Member in $Members)
  91.   {
  92.    if($IsEmpty.IsPresent)
  93.    {
  94.     $Print=0
  95.     break
  96.    }
  97.    $RecipientTypeDetail=$Member.RecipientTypeDetails
  98.    $MemberEmail=$Member.PrimarySMTPAddress
  99.    if($MemberEmail -eq "")
  100.    {
  101.     $MemberEmail="-"
  102.    }
  103.    #Get Counts by RecipientTypeDetail
  104.    foreach($key in [object[]]$Recipienthash.Keys)
  105.    {
  106.     if(($RecipientTypeDetail -eq $key) -eq "true")
  107.     {
  108.      [int]$RecipientHash[$key]+=1
  109.     }
  110.    }
  111.    Print_Output
  112.   }
  113.  }
  114.  
  115.  #Print Summary report
  116.  if($Print -eq 1)
  117.  {
  118.   #Order RecipientTypeDetail based on count
  119.   $Hash=@{}
  120.   $Hash=$RecipientHash.GetEnumerator() | Sort-Object -Property value -Descending |foreach{
  121.    if([int]$($_.Value) -gt 0 )
  122.    {
  123.     if($Recipient -ne "")
  124.     { $Recipient+=";"}
  125.     $Recipient+=@("$($_.Key) - $($_.Value)")    
  126.    }
  127.    if($Recipient -eq "")
  128.    {$Recipient="-"}
  129.   }
  130.   $Result=@{'DisplayName'=$DisplayName;'PrimarySmtpAddress'=$EmailAddress;'Alias'=$Alias;'GroupType'=$GroupType;'Manager'=$Manager;'GroupMembersCount'=$MembersCount;'MembersCountByType'=$Recipient;'AuthorizedSenders'=$AuthorizedSenders;'ExternalSendersBlocked'=$ExternalSendersAllowed <#;'HiddenFromAddressList'=$_.HiddenFromAddressListsEnabled;
  131.  'Description'=$_.Description;'CreationTime'=$_.WhenCreated;'DirSyncEnabled'=$_.IsDirSynced;'JoinGroupWithoutApproval'=$_.MemberJoinRestriction;'LeaveGroupWithoutApproval'=$_.MemberDepartRestriction #>} #Uncomment to print additional attributes in output
  132.   $Results= New-Object PSObject -Property $Result
  133.   $Results | Select-Object DisplayName,PrimarySmtpAddress,Alias,GroupType,Manager,GroupMembersCount,AuthorizedSenders,ExternalSendersBlocked,MembersCountByType <#,HiddenFromAddressList,Description,CreationTime,DirSyncEnabled,JoinGroupWithoutApproval,LeaveGroupWithoutApproval #>  | Export-Csv -Path $ExportSummaryCSV -Notype -Append
  134.  }
  135. }
  136.  
  137. #Print Detailed Output
  138. Function Print_Output
  139. {
  140.  if($Print -eq 1)
  141.  {
  142.   $Result=@{'DisplayName'=$DisplayName;'PrimarySmtpAddress'=$EmailAddress;'Alias'=$Alias;'Members'=$Member;'MemberEmail'=$MemberEmail;'MemberType'=$RecipientTypeDetail}
  143.   $Results= New-Object PSObject -Property $Result
  144.   $Results | Select-Object DisplayName,PrimarySmtpAddress,Alias,Members,MemberEmail,MemberType | Export-Csv -Path $ExportCSV -Notype -Append
  145.  }
  146. }
  147.  
  148.  
  149. Function main()
  150. {
  151.  #Clean up session
  152.  Get-PSSession | Remove-PSSession
  153.  
  154.  #Authentication using MFA
  155.  if($MFA.IsPresent)
  156.  {
  157.   $MFAExchangeModule = ((Get-ChildItem -Path $($env:LOCALAPPDATA+"\Apps\2.0\") -Filter CreateExoPSSession.ps1 -Recurse ).FullName | Select-Object -Last 1)
  158.   If ($MFAExchangeModule -eq $null)
  159.   {
  160.    Write-Host  `nPlease install Exchange Online MFA Module.  -ForegroundColor yellow
  161.    
  162.    Write-Host You can install module using below blog : `nLink `nOR you can install module directly by entering "Y"`n
  163.    $Confirm= Read-Host Are you sure you want to install module directly? [Y] Yes [N] No
  164.    if($Confirm -match "[yY]")
  165.    {
  166.      Write-Host Yes
  167.      Start-Process "iexplore.exe" "https://cmdletpswmodule.blob.core.windows.net/exopsmodule/Microsoft.Online.CSE.PSModule.Client.application"
  168.    }
  169.    else
  170.    {
  171.     Start-Process 'https://http://o365reports.com/2019/04/17/connect-exchange-online-using-mfa/'
  172.     Exit
  173.    }
  174.    $Confirmation= Read-Host Have you installed Exchange Online MFA Module? [Y] Yes [N] No
  175.    
  176.     if($Confirmation -match "[yY]")
  177.     {
  178.      $MFAExchangeModule = ((Get-ChildItem -Path $($env:LOCALAPPDATA+"\Apps\2.0\") -Filter CreateExoPSSession.ps1 -Recurse ).FullName | Select-Object -Last 1)
  179.      If ($MFAExchangeModule -eq $null)
  180.      {
  181.       Write-Host Exchange Online MFA module is not available -ForegroundColor red
  182.       Exit
  183.      }
  184.     }
  185.     else
  186.     {
  187.      Write-Host Exchange Online PowerShell Module is required
  188.      Start-Process 'https://http://o365reports.com/2019/04/17/connect-exchange-online-using-mfa/'
  189.      Exit
  190.     }    
  191.    }
  192.  
  193.   #Importing Exchange MFA Module
  194.   . "$MFAExchangeModule"
  195.   Write-Host Enter credential in prompt to connect to Exchange Online
  196.   Connect-EXOPSSession -WarningAction SilentlyContinue
  197.   Write-Host `nReport generation in progress...
  198.  }
  199.  #Authentication using non-MFA
  200.  else
  201.  {
  202.   #Storing credential in script for scheduling purpose/ Passing credential as parameter
  203.   if(($UserName -ne "") -and ($Password -ne ""))
  204.   {
  205.    $SecuredPassword = ConvertTo-SecureString -AsPlainText $Password -Force
  206.    $Credential  = New-Object System.Management.Automation.PSCredential $UserName,$SecuredPassword
  207.   }
  208.   else
  209.   {
  210.    $Credential=Get-Credential -Credential $null
  211.   }
  212.   $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Credential -Authentication Basic -AllowRedirection
  213.   Import-PSSession $Session -CommandName Get-DistributionGroup,Get-DistributionGroupMember -FormatTypeName * -AllowClobber | Out-Null
  214.  }
  215.  
  216.  #Set output file
  217.  $ExportCSV=".\DistributionGroup-DetailedMembersReport_$((Get-Date -format yyyy-MMM-dd-ddd` hh-mm` tt).ToString()).csv" #Detailed report
  218.  $ExportSummaryCSV=".\DistributionGroup-SummaryReport_$((Get-Date -format yyyy-MMM-dd-ddd` hh-mm` tt).ToString()).csv" #Summary report
  219.  
  220.  #Get a list of RecipientTypeDetail
  221.  $RecipientTypeArray=Get-Content -Path .\RecipientTypeDetails.txt -ErrorAction Stop
  222.  $Result=""  
  223.  $Results=@()
  224.  
  225.  #Check for input file
  226.  if([string]$GroupNamesFile -ne "")
  227.  {
  228.   #We have an input file, read it into memory
  229.   $DG=@()
  230.   $DG=Import-Csv -Header "DisplayName" $GroupNamesFile
  231.   foreach($item in $DG)
  232.   {
  233.    Get-DistributionGroup -Identity $item.displayname | Foreach{
  234.    $Print=1
  235.    Get_Members}
  236.    $Count++
  237.   }
  238.  }
  239.  else
  240.  {
  241.   #Get all distribution group
  242.   Get-DistributionGroup -ResultSize Unlimited | Foreach{
  243.   $Print=1
  244.   Get_Members
  245.   $Count++}
  246.  }
  247.  #Open output file after execution
  248.  Write-Host `nScript executed successfully
  249.  if((Test-Path -Path $ExportCSV) -eq "True")
  250.  {
  251.   Write-Host Detailed report available in: $ExportCSV
  252.   Write-host Summary report available in: $ExportSummaryCSV
  253.   $Prompt = New-Object -ComObject wscript.shell  
  254.   $UserInput = $Prompt.popup("Do you want to open output file?",`  
  255.   0,"Open Output File",4)  
  256.   If ($UserInput -eq 6)  
  257.   {  
  258.    Invoke-Item "$ExportCSV"  
  259.    Invoke-Item "$ExportSummaryCSV"
  260.   }
  261.  }
  262.  Else
  263.  {
  264.   Write-Host No DistributionGroup found
  265.  }
  266.  #Clean up session
  267.  Get-PSSession | Remove-PSSession
  268.  
  269. }
  270.  . main
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement