The issue here is that the EmailAddresses property is a collection of all the aliases for the recipient. If you do Get-Help about_Comparison_Operators
, you will seen that
When the input is a collection of values, the
comparison operators return any matching values.
So your Where-Object call is returning the recipients that have at least 1 email alias that does not match the string you've specified. So the Where-Object syntax you've got will only filter out those recipients that only have 1 alias -- one that matches the string in your filter.
If your aliases follow a naming scheme/policy, you might want to work with the -NotContains
operator instead. This would looks something like this:
Get-Recipient | ? {$_.EmailAddresses -notcontains "smtp:$($_.samaccountname)@abc.com"} |
select samaccountname, emailaddresses | sort samaccountname
You would of course need to alter the string to match the expected alias you're looking to exclude.
EDIT: If you don't have a naming scheme, as you say, then the best I could come up with looks like this:
foreach ($recipient in (Get-Recipient)) {
if ($recipient.EmailAddresses | ? {$_ -like "*abc.com"}) {
#do nothing
} else {
$recipient
}
}
Now, I'm sure there's a better way to do that, but that's the basic logic that should work for you.