powershellif-statementget-aduser

Filter AD Users if one Property is Filled and one is empty


Im trying to get a list of all ADUsers that have there mail property filled and where the proxyAddresses property is empty.

First i got the ADUsers and allready tried to filter to only get thoose whith filled mail property.

$ADUser = get-adUser  -Properties Name,Mail,proxyAddresses -Filter {mail -like '*'}| Where {$_.samAccountname -match "(our naming scheme)"}

then i tried to just put it trough a foreach with an embedded if statement

 foreach ($User in $ADUser) {
 
    if(($User).mail -ne $null -and ($User).proxyAddresses -eq $null)
    {
       $Users += $_.Name
    }

 }

I double checked the mail statement because i found some ADUsers in $ADUser that dont have the mail property filled.

Since im horribly bad with Powershell or scripting at all, I would guess it's quite a simple mistake. But nothing gets passed in my $User variable.

It has to be a problem in my If Statement since i can do a

Write-Host $User

inside of the Foreach loop and it will output the $User

I tryed around for a bit now and even when i just plain do:

 $Test = get-adUser -Properties proxyAddresses -Filter * 
 ($Test).proxyAddresses |Format-List

I cant find an empty property in the list, im pretty sure there are some with empty propertys but somehow i cant find or match them.

Update:

Found a Workaround instead of filtering in the beginning for ADUsers with set Mail properties i now check for Users withouth something in the proxyAddresses property with:

$ADUser = Get-ADUser -Properties Name,Mail,proxyAddresses -Filter {-not(proxyAddresses -like '*')} 

Afterwards i just use the foreach and if loop to check for the mail property.

$result = foreach ($User in $ADUser) {
 
    if($User.mail -ne $null)
    {
      Write-Output($User).Name
    }
    else{
    }
 }

 $result | Out-File -FilePath 'C:\temp\proxAddressesFilter.csv'

Sadly i aint sure why it didnt work with the first version, but at least it works now.


Solution

  • Changed which property i check for first, now i only get ADUsers with empty proxyAddresses property and later on check if something is in the mail property.

    $ADUser = Get-ADUser -Properties Name,Mail,proxyAddresses -Filter {-not(proxyAddresses -like '*')} 
    
     $result = foreach ($User in $ADUser) {
     
        if($User.mail -ne $null)
        {
          Write-Output($User).Name
        }
        else{
        }
     }
    
     $result | Out-File -FilePath 'C:\temp\proxAddressesFilter.csv'