My original question was a bit complex. However some cool memebers did manage to help me.
I got the following piece of code from Vesper:
$mailbox=get-mailbox $username
$perms=get-mailboxpermission $mailbox | where {$_.isinherited -eq $false -and $_.user.toString() -ne "NT AUTHORITY\SELF"}
$perms | remove-mailboxpermission $mailbox -confirm:$false
When I run these commands in a Exchange powershell one by one it works beautifully. However when I try to run my complete script with that snippet in it I receive the following error:
Cannot process argument transformation on parameter 'Identity'. Cannot convert the "USERNAME" value of type
"Deserialized.Microsoft.Exchange.Data.Directory.Management.Mailbox" to type
"Microsoft.Exchange.Configuration.Tasks.MailboxIdParameter".
+ CategoryInfo : InvalidData: (:) [Get-MailboxPermission], ParameterBindin...mationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-MailboxPermission
+ PSComputerName : SERVER
Any idea how to solve this?
A quick and dirty solution can be like this:
Be warned, incorrect user of this script can ruin your Exchange organization, probably test that on a single mailbox. The script is NOT tested, although complies with manuals on both Exchange and Powershell.
Explanation: First line gets the mailbox in question. Second line first gets full ACL on Exchange mailbox object, then filters only those entries that are not inherited
$_.IsInherited -eq $false
and filters outNT AUTHORITY\SELF
which is required to be present for someone to ever access the mailbox - this entry is not inherited. Everything else is deemed to be those permissions that you wish to remove (such rights are added on the mailboxes directly, and thus are not inherited). The third line removes the rights determined by callingRemove-MailboxPermission
against a pipeline. Note the-whatif
switch, which makes the cmdlet to display what's about to be done for the administrator to review before launching the script into production.