Advertisement
nilrem2

Remove an Office 365 User from all Distribution Groups

Apr 8th, 2020
2,158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
  2. Write-Host "================ Assign a user to a shared mailbox ================"
  3.  
  4. #$Livecred = New-Object -typename System.Management.Automation.PSCredential -ArgumentList $AdminName, $Pass
  5. $LiveCred = Get-Credential
  6. $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
  7.  
  8. #Connect to office365
  9. Import-PSSession $Session -AllowClobber
  10. Connect-MsolService -Credential $LiveCred
  11.  
  12. $email = Read-Host "Please provide a user's email address to remove from all distribution groups"
  13. $mailbox = Get-Mailbox -Identity $email
  14. $DN=$mailbox.DistinguishedName
  15. $Filter = "Members -like ""$DN"""
  16. $DistributionGroupsList = Get-DistributionGroup -ResultSize Unlimited -Filter $Filter
  17. Write-host `n
  18. Write-host "Listing all Distribution Groups:"
  19. Write-host `n
  20. $DistributionGroupsList | ft
  21. $answer = Read-Host "Would you like to proceed and remove $email from all distribution groups ( y / n )?"
  22. While ("y","n" -notcontains $answer) {
  23.     $answer = Read-Host "Would you like to proceed and remove $email from all distribution groups ( y / n )?"
  24.     }
  25. If ($answer -eq 'y') {
  26.     ForEach ($item in $DistributionGroupsList) {
  27.         Remove-DistributionGroupMember -Identity $item.PrimarySmtpAddress –Member $email –BypassSecurityGroupManagerCheck -Confirm:$false
  28.     }
  29.    
  30.     Write-host `n
  31.     Write-host "Successfully removed"
  32.     Remove-Variable * -ErrorAction SilentlyContinue
  33.     }
  34. Else
  35.     {
  36.     Remove-Variable * -ErrorAction SilentlyContinue
  37.     }
  38.  
  39. Remove-PSSession $Session
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement