Remove AzureAD user from all groups -powershell - 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

Related

Export all disabled DL members to CSV

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

Delete SharePoint Online site collections using powershell

I have been trying to delete site collections from a csv, I'm trying to use a powershell script to get the site URLs to be deleted.
I've tried everything, now that I've run out of ideas I'm opening this question. I'm accepting possibilities other than Powershell
PS: I'm trying to do this without creating anything in the tenant.
This site belongs to a Microsoft 365 group. To delete the site, you must delete the group.
enter image description here
Below are some attempts:
#Modules
Import-Module ExchangeOnlineManagement
Import-Module Microsoft.Online.SharePoint.PowerShell
Import-Module SharePointPnPPowerShellOnline
$site = "https://tenant.sharepoint.com/sites/site"
$mailGroup = "group#onmicrosoft.com"
#First
Remove-UnifiedGroup -Identity $mailGroup-Confirm:$false
Remove-SPOSite -Identity $site -NoWait -Confirm:$false
#Second
Remove-UnifiedGroup -Identity $mailGroup-Confirm:$false
Set-SPOSite -Identity $site -LockState "unlock"
Set-SPOSite -Identity $site -Owner $userCredential.UserName
Remove-SPOSite -Identity $site -NoWait -Confirm:$false
#Third
$SharepointSite = Get-SPOSite $site
Remove-PnPUnifiedGroup -Identity $SharepointSite .GroupID
Remove-PnPTenantSite $site
I also tried what is in the link: https://learn.microsoft.com/en-us/answers/questions/674248/batch-delete-site-collections-in-powershell-from-c.html
Please try to run the command Remove-UnifiedGroup -Identity "group name" to delete the Microsoft 365 group before run Remove-SPOSite -Identity $site -NoWait -Confirm:$false. Note: you may need to wait some time after deleting a group ,then the site can be successfully deleted.

How to run this script against another domain

I have the script below to give me the distinguished name for groups in a spreadsheet I have. The issue is, the groups are located in another domain. How do I point my script to that domain? Issue is I know I have to be logged in to that domain to run it but I cant.
$Groups = Get-Content -Path C:\Scripts\DistinguishedName.csv
ForEach ($Group in $Groups) {
Get-ADGroup -Identity $Group | Select-Object distinguishedName
}
The cmdlets in the Active Directory module support passing in the value of the domain controller you are wanting to query. By default when you call Get-ADGroup (or any of the other) it will validate what domain it should query by checking the domain of your current machine.
The other option is to provide the -Server (doc) with the value of the Active Directory Domain Services you want to execute your query against.
You can also provide the -Credential parameter with a PSCredential object that contains your login for that other domain. This is required if the current login of your PowerShell session is not authorized to authenticate against that other domain.
So your example script would look something like this:
$AdDomain = "whatever.company.local"
$adCred = Get-Credential
$Groups = Get-Content -Path C:\Scripts\DistinguishedName.csv
ForEach ($Group in $Groups) {
Get-ADGroup -Identity $Group -Server $AdDomain -Credential $adCred | Select-Object distinguishedName
}

PowerShell Script to Automate New AD Group Membership

Can anyone share ideas for a PowerShell script that will create a new AD global security group and then populate it with all user objects that share a specific attribute?
Use the ActiveDirectory module.
$group_name = 'dudez'
New-ADGroup -Name $group_name `
-GroupCategory Security `
-GroupScope Global `
-Path "CN=Users,DC=foo,DC=local" `
-Description "Members of this group have identified as men."
$dudes = (Get-ADUser -Filter "...").DistinguishedName
Add-ADGroupMember -Identity $group_name -Members $dudes
First line creates the group. Second builds the list of users you want in the group. Third line adds the users to the group.
You should be able to modify this to suit your needs.

Powershell get computer name and add to AD group

I am trying to utilize Powershell to get the computer name it’s currently running on and then add that computer to a security group and I’m stuck.
Forcing myself to learn Powershell better and got this from a co-worker but not sure how to edit it for my needs. This script will be used to run after a certain package has been installed to grant access. Here is what I have so far:
param(
[string[]]$mname,
[string[]]$gname
)
foreach($m in $mname.split(','))
{
$mobj = get-adcomputer $m
foreach($g in $gname.split(','))
{
Add-ADGroupMember "GROUP_NAME" -Members $mobj
}
}
ERROR:
You cannot call a method on a null-valued expression.
At C:\Scripts\Add-MachineToCollectionGroup.ps1:6 char:15
+ foreach($m in $mname.split(','))
Just add your groupname at the top, also if you aren't running Powershell 5 you may need to change Add-ADGroupMember $groupobj -Members $computerobj to be Add-ADGroupMember $groupobj -Member $computerobj I think they changed that.
Also add -whatif to the end of the last line to test it (It'll tell you what it would have done without the whatif).
Oh also you will need to run this from an account that has AD access to add the machine to the group and the computer must have the activedirectory module installed.
$Groupname = "ENTER GROUP NAME HERE"
$computerobj = Get-ADComputer $env:COMPUTERNAME
$groupobj = Get-ADGroup $Groupname
Add-ADGroupMember $groupobj -Members $computerobj -WhatIf