Need help on sending emails to inactive users

Hi Guys,

I’m trying to send email to inactive users in my organization. I’m new to PowerShell, so need your help. I was able to reuse the script to pull out the users with an email attribute who didn’t log in for 45 days and I managed to create the script for sending emails. It is perfectly working.

Now I need to pass the mail attribute output to a variable and use that variable to send emails.

And I noticed few users don’t have an email attribute, so I want to notify their mangers.

When I run the below command, I’m getting the output of the manager name in distinguished format (“CN=Mamilla, Sampath,OU=LS Users,DC=Contoso,DC=COM”). I’m trying to fetch the manager SAMaccountname and email address.

I did the below customization it didn’t work.

Select-Object @{Manager="manager"; e={(Get-aduser -filter {sAMAccountName -eq $_.Manager}.sAMAaccountName)}}

Need your help.

Import-Module ActiveDirectory

# Set the number of days since last logon
$DaysInactive = 45
$InactiveDate = (Get-Date).Adddays(-($DaysInactive))

#-------------------------------
# FIND INACTIVE USERS
#-------------------------------

# Get AD Users that haven't logged on in 45 days
$Users = Get-ADUser -searchbase "OU=LS Users,DC=Contoso,DC=COM" -Filter { LastLogonDate -lt $InactiveDate -and Enabled -eq $true } -Properties LastLogonDate, mail, manager | Select-Object @{ Name="Username"; Expression={$_.SamAccountName}}, Name, LastLogonDate, mail, manager

$useremail=mail

#Select-Object @{Manager="manager"; e={(Get-aduser -filter {sAMAccountName -eq $_.Manager}.sAMAaccountName)}}

# Export results to CSV
$Users | Export-Csv "E:\thiru\powershellscripts\Finding inactive Users\InactiveUsers.csv" -NoTypeInformation

--------------email script----------------------------------------------------

$From = "Contoso.IT@Contoso.com"
$To = "thiru.dk@Contoso.com"
$Subject = "Network Account Not used"
$Body = "

Hi You haven't used your network account for last 45 days. Your network account will be disabled if you don't login in next 15 days.

<br /><br />" $Body += “Contoso IT" $SMTPServer = "smtp-relay.Contoso.com" $SMTPPort = "25" Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -BodyAsHtml -SmtpServer $SMTPServer -Port $SMTPPort

One option is to write that logic into an EmailTo with a calculated property:

$Users = Get-ADUser -searchbase "OU=LS Users,DC=Contoso,DC=COM" -Filter { LastLogonDate -lt $InactiveDate -and Enabled -eq $true } -Properties LastLogonDate, mail, manager | 
         Select-Object @{ Name="Username"; Expression={$_.SamAccountName}}, 
         Name, 
         LastLogonDate, 
         mail, 
         manager,
         @{Name='EmailTo';Expression={if($_.Mail){$_.Mail}else{Get-aduser -filter {sAMAccountName -eq $_.Manager}.Mail}}}

Still would be wise to wrap an if around that mail send if ($_.EmailTo) {… as a manager could be null.

Hi Rob,

Thanks for your reply. By the time when I was waiting for the reply. I remembered that I had wrapped the whole output
as a variable ($users), and now I can use the dot syntax.

When I ran  $Users.mail - I got the output of all the users email.

I applied the same in the $to variable. But It didn't work. I got the below error message.



-----------------------------Error--------------------------------------------------------------
Send-MailMessage : Cannot validate argument on parameter 'To'. The argument is null, empty, or an element of the argument collection contains a null value. Supply a 
collection that does not contain any null values and then try the command again.
At E:\thiru\powershellscripts\Finding inactive Users\45inactive.ps1:45 char:34
+ Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -B ...
+                                  ~~~
    + CategoryInfo          : InvalidData: (:) [Send-MailMessage], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.SendMailMessage

-----------------------------Error--------------------------------------------------------------

Apologies, I don't understand the below command. I barely have 2 weeks of experience in learning powershell. 
It seems you are applying the label and casting a IF cmd.
 @{Name='EmailTo';Expression={if($_.Mail){$_.Mail}else{Get-aduser -filter {sAMAccountName -eq $_.Manager}.Mail}}}

It will be great if you give me any blog or article which discuss about above usage to understand.



Script


Import-Module ActiveDirectory

# Set the number of days since last logon
$DaysInactive = 45
$InactiveDate = (Get-Date).Adddays(-($DaysInactive))

$Users = Get-ADUser -searchbase "OU=LS Users,DC=Contonso,DC=COM" -Filter { LastLogonDate -lt $InactiveDate -and Enabled -eq $true } -Properties LastLogonDate, mail, manager | Select-Object @{ Name="Username"; Expression={$_.SamAccountName}}, Name, LastLogonDate,  mail , manager


# Export results to CSV
$Users | Export-Csv "E:\thiru\powershellscripts\Finding inactive Users\InactiveUsers.csv" -NoTypeInformation


foreach ($user in $users.email)


$From = "Contonso.IT@Contonso.com"
$to = $users.mail
$Subject = "Network Account Not used"

$Body = "Dear $users.name, 
  <br>
   <br>You haven't logged in to Contonso your network account($U42users.Username) for last 45 days.The account will be disabled unless you log onto the network (for example, myCloud)."

$Body += “<br>
 <br>Contonso IT"
$SMTPServer = "smtp-relay.Contonso.com"
$SMTPPort = "25"

Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -BodyAsHtml -SmtpServer $SMTPServer -Port $SMTPPort

}

 

Take a look at this code. Be careful in your loop that you reference $user, not $users. Cleaned up the code a bit and take a look at the comments.

Import-Module ActiveDirectory
 
# Set the number of days since last logon
$DaysInactive = 45
$InactiveDate = (Get-Date).AddDays(-($DaysInactive))
 
$Users = Get-ADUser -searchbase "OU=LS Users,DC=Contonso,DC=COM" -Filter { (LastLogonDate -lt $InactiveDate) -and (Enabled -eq $true) } -Properties LastLogonDate, mail, manager |
         Select-Object @{ Name="Username"; Expression={$_.SamAccountName}}, 
         Name,
         LastLogonDate,
         mail,
         manager,
         @{Name='EmailTo';Expression={if($_.Mail){$_.Mail}else{Get-aduser -filter {sAMAccountName -eq $_.Manager}.Mail}}}
         #If the mail is not null, use mail, otherwise lookup the managers email address
 
# Export results to CSV
$Users | Export-Csv "E:\thiru\powershellscripts\Finding inactive Users\InactiveUsers.csv" -NoTypeInformation
 
 
foreach ($user in $users) {

#Here String, cannot be indented, 
$body = @"
    <p>Dear $($user.name),</p>
    <br>
    <br>
    <p>
        You haven't logged in to Contonso your network account$($user.Username) for last 45 days. 
        The account will be disabled unless you log onto the network (for example, myCloud)."
    </p>
    <br>
    <br>
    Contonso IT
"@

    #Splatting
    $params = @{
        From       = "Contonso.IT@Contonso.com"
        To         = $users.EmailTo 
        Subject    = "Network Account Not used" 
        Body       = $Body 
        BodyAsHtml = $true
        SmtpServer = "smtp-relay.Contonso.com" 
        Port       = "25"
    }


    Send-MailMessage @params
}

Thanks everyone!

Just a logic point, not an issue with your script. But if your users aren’t logging on, how do you expect them to recieve/read email?

might want to send to the manager and cc the user to ensure it gets visibility :slight_smile:

Hi David,

I thought about it. That’s the reason I also want to pull out the manager email address.

If you see the line number 16 in my original question, i tried to extract but failed. I don’t know the logic on how to extract it.

I got a priority requirement in my office, so working on that. I thought of starting this thread again on Monday. If you are able to help me with on pulling the manager email address along with user email address, that will be great help. Thank you.

#Select-Object @{Manager="manager"; e={(Get-aduser -filter {sAMAccountName -eq $_.Manager}.sAMAaccountName)}}