A powershell novice here managed to disable several hundred accounts using this. When testuser1 is not found the get-mailbox ignores the identity and proceeds to modify every account it can before you catch it!
First, I’d suggest explicitly using a parameter rather than passing $user.name positionally. Just as a good practice.
Second, you should be testing $user to make sure it contains something before using it. Right now, your code is assuming $user is valid, and that assumption is the problem. It isn’t so much “reasoning;” if $user is empty, then it… well, it doesn’t exist, so it doesn’t need to be attached to a parameter positionally, so Get-Mailbox runs as if it was given no input - and gets all mailboxes.
Get-QADUser is different from Get-ADUser. It can return multiple matches (ANR search?) or nothing, with no error. If you have to use it, use the DN as the identity, or use an ldapfilter search. Also, remember your good friend -whatif, when running off the cuff scripts. I assume there was more to the script then you put in your post, you retrieved msExchRecipientTypeDetails and then didn’t test it before changing the mailbox.
the problem really in exchange cmdlets
just test Get-Mailbox $null / Get-Mailbox -Identity $null and you get it
I think Exchange team use ($Identity -eq $null) and should use ($PSCmdletBinding.ContainsKey(‘Identity’)) for retrieving all mailboxes
I think this artefact from v1.0 days