Home > Enterprise >  Multiple input loop for the Remove-AzureADGroupMember cmdlet?
Multiple input loop for the Remove-AzureADGroupMember cmdlet?

Time:06-09

All,

Script to show all Azure AD groups of which the $User is a member of.

$User = 'Compromised.UserAccount'
$UserToRemove = Get-AzureADUser -SearchString $User

$UserToRemove |
    Get-AzureADUserMembership | 
    ForEach-Object { Get-AzureADObjectByObjectId -ObjectId $_.ObjectId | Get-AzureADGroup | Where-Object {$_.OnPremisesSecurityIdentifier -eq $null} | Select-Object DisplayName, ObjectType, MailEnabled, SecurityEnabled, ObjectId } |
    Out-GridView -Title "$($User) account Cloud Only Group membership"

I need to pipe the output above to the https://docs.microsoft.com/en-us/powershell/module/azuread/remove-azureadgroupmember?view=azureadps-2.0

The goal here is to be able to delete or remove the $User from all AzureADGroup where he/she is a member in the Out-GridView list above.

Remove-AzureADGroupMember -ObjectId ...  -MemberId $UserToRemove.ObjectId

Thank you in advance.

CodePudding user response:

I would split it up into more distinct commands instead of a single pipeline:

$User = 'Compromised.UserAccount'
$AzUser = Get-AzureADUser -SearchString $user
$AzMemberships = $azUser | Get-AzureADUserMembership
$AzGroups = Get-AzureADObjectByObjectId -ObjectIds $AzMemberships.objectID

$CloudGroups = $AzMemberships | Where-Object {$_.OnPremisesSecurityIdentifier -eq $null}

# Display cloud groups
$CloudGroups | Select-Object DisplayName, ObjectType, MailEnabled, SecurityEnabled, ObjectId |
  Out-GridView -Title "$($User) account Cloud Only Group membership"

# Remove user from all cloud groups
Foreach ($cloudGroup in $cloudGroups) {
  Remove-AzureADGroupMember -ObjectId $cloudGroup.ObjectID -MemberId $AzUser.ObjectId
}
  • Related