I'm trying to list all groups that contain a specific SMTP address in the group. Below is the code I'm using but its outputting everything and not just the groups with the specified SMTP address:
$temp = Get-DistributionGroup -ResultSize Unlimited
foreach ($group in $temp)
{
if (Get-DistributionGroupMember $group | select -ExpandProperty PrimarySmtpAddress`
| ForEach-Object {$_.PrimarySmtpAddress -match "contoso.com"}) {
Write-Output "GroupName:$group "
Write-Output "GroupName:$($group.PrimarySmtpAddress) "
Write-Output "GroupMembers:"
Get-DistributionGroupMember $group|ft displayname,primarysmtpaddress
}
else
{
Write-Host "null"
}
}
That doesn't work because your if statement just tests whether the code in the condition executes successfully, and there's no reason why it would fail for any group. There's nothing in the logic that makes the condition false if the Foreach-Object block doesn't find any matches. Try this:
foreach ($group in $temp) {
if ((Get-DistributionGroupMember $group | %{$_.PrimarySmtpAddress}) -match 'contoso\.com') {
[...]
(Get-DistributionGroupMember $group | %{$_.PrimarySmtpAddress})
creates an array of the PrimarySmtpAddress properties of all the members, then the if condition tests whether it matches the regex (-match applied to an array returns an array of all elements that match, so it's true if at least one element matches, false if the array is empty).
Note, BTW, that the string to right of the -match operator is a regex, not a literal string. That's why I added the backslash. In a regex, .
matches any single character, so -match 'contoso.com'
would match strings like contososcom
and contoso?com
.