Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compare 2 ActiveDirectory properties using Powershell

My Goal is to List all ADusers where the property proxyAddresses does not contain the value from the mail property.

My first step is to get all users that have both values filled with:

$ADUser = Get-ADUser -Properties Name,Mail,proxyAddresses -Filter {proxyAddresses -like '*' -and mail -like '*'}

then i try to run it trough a foreach loop with an integrated if statement

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$result = foreach ($User in $ADUser){
$proxystring = $User.proxyAddresses
    $Mailstring = $User.Mail

    $Mailstring = $Mailstring.ToString()
                
    if ($proxystring -contains '*$Mailstring*'){

    Write-Host 'läuft'
    }
    
    else{
    
    Write-Output($User).Name

    }
}

in the if statement i tried

if ($proxystring -contains '*$Mailstring*')
if ($proxystring -contains $Mailstring)
if ($proxystring -like $Mailstring)
if (($proxystring).contains($Mailstring))

As in the mainpart of the Code seen, I also tried to pass it to a string because i thought the format might be a problem.

Everywhere i looked a variable only gets matched with a string, not with other variables.

If anyone happens to know what my mistake is i would be grateful.

>Solution :

You would need to remove the preceding SMTP: / smtp: from each address in proxyAddresses for this to work properly:

$result = :outer foreach ($User in $ADUser){
    foreach($address in $user.proxyAddresses) {
        # remove the leading `smtp:` from each address
        $mail = $address -replace '^smtp:'
        # and compare, if the user's mail was in the `proxyAddresses` array
        if($mail -eq $User.mail) {
            # there is no need to keep checking, we can skip this user
            # and go next
            continue outer
        }
    }
    # if the user's `mail` wasn't found in the `proxyAddresses` array
    # output this user
    $user
}

You could also use -notcontains to simplify the above code a lot but this requires prepending smtp: to user’s mail attribute:

$result = foreach ($User in $ADUser){
    if($user.proxyAddresses -notcontains ('smtp:' + $user.mail)) {
        $User
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading