Still Learning Powershell - foreach with if statement not working as expected

Hello,

I am trying to return a list of users that have email addresses, excluding those that do not.

Actually, I am working on a larger script, but have broken down the script to a section that isn’t working. When I run the script it erroneously does two things:

  1. it returns the full list of users even if they do not have an email address, even though I manually verified that at least some do not.
  2. it doesn’t process the select statement nested within the if statement.

In other words, it does not process the Else statement, which is to write-host “no email…” for the users that do not have an email.

Below is the code. Please let me know if you can help.

 # Get Users From AD who are Enabled, and who has not logged in in over 45 days 
#InactiveDays 
$45Days     = (get-date).adddays(-45) 
$55Days     = (get-date).adddays(-55) 
$OU1        = "OU1Example" 
$users = Get-Aduser -Properties Name, EmailAddress, lastlogondate -Filter {(lastlogondate -le $45days -and LastLogonDate -ge $55days) -and (enabled -eq $True) -and (whencreated -le $45days) } |      
    Where-Object {$_.distinguishedname -notlike $OU1}   

# Process Each User for Last Logon Date 
foreach ($user in $users) 
{ 	
    $Name = (Get-ADUser $user | ForEach-Object { $_.GivenName +" "+ $_.SurName})     
$username = (Get-ADUser $user | ForEach-Object { $_.SamAccountName})     
$emailaddress = $users.EmailAddress 	
    Write-Host "Working on $Name..." -ForegroundColor White 	
    Write-Host "Getting e-mail address for $username..." -ForegroundColor Yellow     	
    If($emailaddress -like "*") {         
    Select name, @{Name="UserID";Expression={$_.SamAccountName}}, EmailAddress, lastlogondate, DistinguishedName | ft -property Name, UserID, EmailAddress, LastLogonDate, DistinguishedName 	
    } Else {          
    Write-Host "$Name has no E-Mail address listed." -ForegroundColor Red 
} 
}

It’s because you’re assigning the entire list of emails to $emailaddress. ($users instead of $user) A very good habit is to use descriptive variables and avoid plural/singular as it’s easy to over look… as you have learned the hard way.

Foreach($user in $userlist){…} 

You’d see it more easily if I accidentally put $userlist in my loop instead of $user. Where $users vs $user isn’t

2 Likes

ok! I get it!

I was able to change it to $user and it works now. I will also take your suggestion and avoid plural/singular use!

1 Like