Export all disabled DL members to CSV - powershell

I have an issue I've not been able to work through and I'm hoping I can get assistance. I've taken over management of 15,000+ AD user accounts and almost 1500 o365 distribution groups. I have been trying to build a command or script to query all distribution groups and export a list of user accounts that are members and do not have a mailbox.
I was able to get a working script that will find and remove them all however it is keying of disabled user accounts which would remove members that should not be. I only need group members removed that do not have a mailbox in o365. Ideally, I'd like to query the groups and export the list of group members without a mailbox to a CSV and include Name, AccountName and AccountDisabled. Any assistance would be appreciated.
Failed attempt:
$dg = Get-DistributionGroup
foreach($group in $dg){
Get-DistributionGroupMember -Identity $group.identity | ?{$_.recipienttype -eq 'UserMailbox'} |
foreach{
$mbx = Get-Mailbox $_.alias
if($_.name -eq $mbx.name -and $mbx.AccountDisabled -eq $true){
write-host "Removing User:" $_.alias "from group:" $group.identity
remove-distributiongroupmember -Identity $group.Identity -Member $_.alias -Confirm:$false
Write-Host "User Successfully Removed"
}
}
}
This is the command I found which will output the user and group name to the screen and remove the group member however it is keying off disabled AD User accounts and it's outputting it in a format that won't export to csv.
Thank you
Pat

Related

Remove AzureAD user from all groups -powershell

I've been trying to remove all of the groups(M365,DL,security etc.) from a user.
I was trying to use this script but I'm getting errors when removing DLs(reasonably).
$Groups = Get-AzureADUserMembership -ObjectId $userID
foreach($Group in $Groups.ObjectId){
Remove-AzureADGroupMember -ObjectId $Group -MemberId $userID
}
My problem is that I have no way to get the type of the group and treat it with the correct command accordingly. When trying to use MSOL to get the type I saw that M365 groups are also being shown as a distribution list, So I'm not able to use this method.
Any advice or luck with that?
Thanks!
Edit:
This is how the groups are showing up, identical but not actually as it requires different command to remove the group.
365 group and DL
Considering that Azure AD group memberships can be removed via Remove-AzureAdGroupMember while Exchange Online memberships via Remove-DistributionGroupMember, executing both commands via a try..catch is probably the most efficient way to meet the OP's requirements.
The code below does just that (remove the comment before the Confirm parameter to skip confirmation.)
Connect-AzureAD
Connect-ExchangeOnline
$userid = (Get-AzureADuser -objectid "test.user#testdomain.test").objectid
$Groups = Get-AzureADUserMembership -ObjectId $userID
foreach($Group in $Groups){
try {
Remove-AzureADGroupMember -ObjectId $Group.ObjectID -MemberId $userID -erroraction Stop
}
catch {
write-host "$($Group.displayname) membership cannot be removed via Azure cmdlets."
Remove-DistributionGroupMember -identity $group.mail -member $userid -BypassSecurityGroupManagerCheck # -Confirm:$false
}
}
Note: proper code formatting does help.
I have tried with same script in my environment to remove an user from the groups and it removed successfully .
Azure portal->Groups->Enter your Group name
In my Azure Active directory ,I have Microsoft group type with 5 users:
In my Security Group type I have 4 users:
I tried with particular user like imran khan to remove from these two groups.
First you need to connect with azureAD using this command :
Import-Module AzureAD
$Credential = Get-Credential
Connect-AzureAD -Credential $Credential
Now I tried with same commands:
$userID = 'user object ID'
$Groups = Get-AzureADUserMembership -ObjectId $userID
foreach($Group in $Groups.ObjectId){
Remove-AzureADGroupMember -ObjectId $Group -MemberId $userID
}
Response:
Which returned empty that means which I removed successfully a user from the group.
Reference:
Compare groups - Microsoft 365 admin | Microsoft Docs

Script to copy Exchange Distribution Groups from one user to another

I am hoping to get some help with a script to copy Exchange group permissions from one user to another. I currently have a script that works to copy mailbox permissions from one user to another but would like to expand it so that it can do Distribution Groups as well.
Connect-ExchangeOnline
$FUser = Read-Host "Enter the email address of the user you want to copy mailbox permissions from"
$TUser = Read-Host "Enter the email address of the user you want to set mailbox permissions for"
$GPerm = Get-Mailbox | Get-MailboxPermission -User $FUser
$GPerm | ForEach-Object { $_
Add-MailboxPermission -Identity $_.Identity -AccessRights FullAccess -InheritanceType All -User $TUser
Add-RecipientPermission -Identity $_.Identity -AccessRights SendAs -Confirm:$false -Trustee $TUser
}
While looking online I found a similar question online asked by someone else but their question was about coping the DL members from one to another DL.
Get-DistributionGroupMember -Identity "A" | % {add-distributiongroupmember -Identity "B" -Member $_.Name}
Additonally I was able to find a script working to remove the permissions for DLs. But didn't work if I changed the parts from remove to add. But the script isn't for what I am looking for as removing permissions and copying are two different things.
Thanks,
daaqis

How to copy Office 365 group membership to another group?

I'm hoping there is a powershell command that can copy the group membership of an O365 group to a different O365 group. I got this from the web, but it's not working because my source group "is not a valid mailbox recipient."
Get-DistributionGroupMember -Identity "Source Group Name" |% {Add-DistributionGroupMember -Identity "Destination Group Name" -Member $_.PrimarySmtpAddress}
Try this:
$members = Get-DistributionGroupMember -Identity "Source Group Name"
Add-DistributionGroupMember -Identity "Destination Group Name" -Member $members
if that doesn't work:
$members = Get-DistributionGroupMember -Identity "Source Group Name"
foreach ($item in $members) {
Add-DistributionGroupMember -Identity "Destination Group Name" -member $item
}
All depends on if the -member parameter accepts an array or a single object. The documentation for the cmdlet is specific to exchange not OFfice 365 and could be a little dated. The documentation seems to indicate the -member parameter will not accept an array of objects so I suspect you'll have to use the 2nd approach.
This might be well known, but for those searching for this answer in the future, an Office 365 group is called a Unified Group in powershell. So I ended up figuring out how to do it with the below code:
$members = Get-UnifiedGroupLinks -Identity "Source O365 Group Name"
foreach ($item in $members) {
Add-UnifiedGroupLinks -Identity "Destination O365 Group Name" -LinkType Members -Links $item.primarysmtpaddress
}
Thanks for your help in constructing the code Zack A!

Get-ADUser using old pre-Windows 2000 Logon name instead of CN

I'm trying to use Add-ADGroupMember cmdlet in PowerShell, but I've realized PS doesn't recognize the object if I use the CN, and it only seems to recognize the pre-Windows 2000 logon name.
That attribute had a character limitation of 20 characters, so some of our accounts have different CNs and Pre-Windows 2000 logon names.
My whole process is:
Step 1: Get a list of my users (this gives me the legacy pre-Windows 2000 logon names):
Get-ADUser -Filter {department –notlike “Field”} –SearchBase “OU=Accounts,OU=HQ,OU=Production,DC=MYDC,DC=MYDC1,DC=MYDC2” -Properties department | select name | Out-file C:\Users\Public\Users.txt
Step 2: Add those users to my security group:
$UserList = Get-Content "C:\Users\Public\Users.txt"
$GroupName = "MY-SEC-Group"
$Members = Get-ADGroupMember -Identity $GroupName -Recursive | Select -ExpandProperty SAMAccountName
ForEach ($user in $UserList)
{
If ($Members -contains $user)
{
Write-Host "$user is member of $GroupName"
}
Else
{
Write-Host "$user is not a member. Attempting to add now, run script again for verification"
Add-ADGroupMember -Identity $GroupName -Members $User
}
}
For all accounts where the legacy logon name and the CN are the exact same, there are no issues. But in situations where they are different, I get the error "Object not found"
Is there a better/more up-to-date cmdlet to use? Maybe one that relies on the CN instead of the legacy logon name? Or do I need to add in CN to all my scripts now?
Get-ADGroupMember returns objects that point to the concrete user in ActiveDirectory and contain different fields including distinguishedName, SamAccountName , SID, Name and so on. In your code you create a txt file with Names (not SamAccountName) but use SamAccountName in Get-ADGroupMember. So, you just compare names with SamAccountName values (that's incorrect).
Just replace
select name | Out-file C:\Users\Public\Users.txt
with
select SamAccountName | Out-file C:\Users\Public\Users.txt
SamAccountName (just as SID) is the unique attribute in AD -
https://blogs.technet.microsoft.com/389thoughts/2017/02/03/uniqueness-requirements-for-attributes-and-objects-in-active-directory/ so, you should use it in your code.

Remove full access permissions of all disabled users on shared mailboxes with exchange management shell

I’m looking for a powershell exchange script to remove Full access permissions of all disabled users on all shared mailboxes in a specific OU.
This is what I got so far
Remove-MailboxPermission -Identity Sharedmailbox -AccessRights Fullaccess -InheritanceType all -user DisabledUser -Confirm:$false | where {$_.UseraccountControl -like "*accountdisabled*"}
Its seems to work but I’m not sure about the last piece of het script if it will check for “accountdisabled”
Then I created a variable so it will check only one specific OU
$ou = Get-ADUser -SearchBase "OU=Functional Mailboxes,OU=Generalaccounts,DC=DOMAIN,DC=COM" -Filter * foreach ($user in $ou)
Remove-MailboxPermission -Identity "$ou" -AccessRights Fullaccess -InheritanceType all -Confirm:$false | where {$_.UseraccountControl -like "*accountdisabled*"}
The script is checking the right OU but I'm still looking for the last part where it will automatically remove full access permissions of the disabled users ONLY.
Can someone show me the way?
Instead of trying to screen for disabled users after removing the mailbox permissions (which is what your Remove-MailboxPermission ... | Where-Object ... appears to be intended to do - except that the way you wrote it, it's only checking for disabled state after removing the permissions), try selecting for the disabled accounts first, then passing only the disabled accounts to Remove-MailboxPermission:
Get-ADUser -SearchBase ... -filter {Enabled -eq $false} | Remove-Mailbox ...
(replacing ... with the appropriate SearchBase or parameters for Remove-Mailbox, using $_ for the identity of the ADUser whose mailbox permissions you're removing.)