Home > Mobile >  Compare 2 ActiveDirectory properties using Powershell
Compare 2 ActiveDirectory properties using Powershell

Time:11-15

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

$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.

CodePudding user response:

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
    }
}
  • Related