arraysstringpowershellobjectpsobject

Powershell array objects type being changed to string after using .Replace(), unable to compare to another array, which also claims to contain strings


I am currently working with Exchange Online and Graph to update my company's distribution groups.

The issue I'm encountering is when dealing with external users in my environment. When I am initially pulling the list of external users they all contain the substring "#EXT#@company.com". No problem, easily fixed by including ($_.UserPrincipalName.Replace("#EXT#@company.com", "")) in my Where-Object statement. However after doing so, I am now unable to compare the objects in this array to the array of current group members.

I'm not getting any kind of error, but in my comparison function, I am no longer finding any common items between the two arrays. For reference I am in VSCode, when I hover over the list of group members, I see an array of System.Management.Automation.PSObject. However the list where I have replaced the substring is now an array of System.String objects.

I have tried using GetType() on both of these arrays, as well as the items in the arrays. Both arrays claim to be System.Array.Object, and the objects within both arrays claim to be System.Object.String.

Here is a sample of my code to better understand what is going on here:

Code to get new list of users:

$ExternalUsers = ($allActiveUsers | Where-Object {($_.Mail -notmatch ".*company\.onmicrosoft\.com$|.*@company\.com$" -and ($_.UserPrincipalName.Replace("#EXT#@company.com", "")) -notmatch ".*company\.onmicrosoft\.com$|.*@company\.com$")} | Select-Object -ExpandProperty UserPrincipalName).Replace("#EXT#@company.com", "")

Code to get list of current distribution group members:

$GrpExternalUsersMembers = Get-DistributionGroupMember -Identity "GrpExternalUsers" | Select-Object -ExpandProperty PrimarySmtpAddress

And here is the code I am using to compare the two, and remove any users necessary:

$usersToRemove = $distributionGroupMembers | Where-Object{$currentUsersList -notcontains $_}
        if ($usersToRemove) {
            Write-Output "Removing $($usersToRemove.Count) users from distribution group '$distributionGroupName'"
        }
        foreach ($user in $usersToRemove) {
            Write-Output "Remove $user"#Remove-DistributionGroupMember -Identity $distributionGroup.Id -Member (Get-MgUser -UserID $_).Id
        }

Ideally I would prefer to not convert everything to strings, I was hoping there is some way to preserve the original object array.

Any help would be greatly appreciated!


Solution

  • Solved:

    When storing these external users, exchange will replace the "@" symbol in the User Principle Name with an "_", leaving the emails to look like this: exampleemail_outlook.com#EXT#@company.com. This issue was resolved by changing Select-Object -ExpandProperty UserPrincipalName to Select-Object -ExpandProperty Mail.