Search code examples
powershelloffice365

Powershell remove multiple shared mailboxes from multiple users


Right now I have a function that removes multiple shared emails from a single user. But, I'd like to be able to specify multiple users that also need the multiple shared emails removed from their accounts as well. I can't think of a good way to do this?

Here is what I have so far and it works, but I can only specify one user on the -user parameter.

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string[]]$address,

        [Parameter(Mandatory = $true)]
        [string]$user
    )
    foreach ($mailbox in $address) {
        Remove-MailboxPermission `
            -Identity $mailbox `
            -AccessRights FullAccess `
            -Confirm:$false `
            -User $user

        Remove-RecipientPermission `
            -Identity $mailbox `
            -AccessRights SendAs `
            -Confirm:$false `
            -Trustee $user

        Set-Mailbox $mailbox -GrantSendOnBehalfTo @{remove = "$user" }
    }
} #function Remove-SharedMailbox```

Solution

  • Continuing from my comment:

    function Remove-SharedMailbox {
        [CmdletBinding()]
        param (
            [Parameter(Mandatory = $true)]
            [string[]]$address,
    
            [Parameter(Mandatory = $true)]
            [string[]]$user
        )
        foreach ($mailbox in $address) 
        {
            foreach ($account in $user)
            {
                Remove-MailboxPermission `
                    -Identity $mailbox `
                    -AccessRights FullAccess `
                    -Confirm:$false `
                    -User $account
    
                Remove-RecipientPermission `
                    -Identity $mailbox `
                    -AccessRights SendAs `
                    -Confirm:$false `
                    -Trustee $account
    
                Set-Mailbox $mailbox -GrantSendOnBehalfTo @{remove = $account }
            }
        }
    }
    

    it's ultimately the same logic you're already using just in a nested loop. Just made $user to accept an array of strings by casting [string[]] to it. The nested loop iterates through the users passed to it using $account.