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?