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:
- 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.
- 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
}
}