0

Scenario : If an account is enabled and its expire date is less than 30 days, send email to their manager.

Problem: My powershell script sends email to manager of accounts both when user is enabled and disabled, I tried to change something in the IF sats cause I feel something is wrong there but still not able to solve the problem. Does anyone have any idea how/where should I change in this script?

import-module ActiveDirectory;

Get-ADUser -Filter * -SearchBase 'OU=Product Owners,OU=Employees,OU=Cloud Users,DC=0000,DC=0000' -Properties directReports, EmailAddress, Displayname | ForEach {
 $ManagerName = $_.Displayname
Write-Host $_.directReports
$Body = "
                        <html>
                        <body> 
                        <p style='font-size:12.0pt;font-family:Arial'>Hej $ManagerName,<br/><br>
                        Du har f&aring;tt detta mail f&ouml;r att du &auml;r ansvarig f&ouml;r de personer som listas nedan. De har &aring;tkomst till sina rika PIM-klienter via VPN.<br><br>
                        <style>
                        TABLE {font-family:Arial; border-width: 0px; border-style: solid; border-color: black; border-collapse: collapse; border-spacing: 0;}
                        TH {border-width: 1px; padding: 7px; border-style: solid; border-color: black; background-color: #2079B5; color: white;}
                        TD {border-width: 1px; padding: 7px; border-style: solid; border-color: black;}
                        </style>
                        <table>
                        <tbody>
                        <tr><th>Namn</th><th>E-postadress</th><th>Kontots utg&aring;ngsdatum</th></tr>";
$AddBody = "";

If ($_.directReports)
{
 
 Write-Output("Processing : " + $ManagerName);
 $ToEmail = $_.EmailAddress
 
 $_.directReports | ForEach {
  
  $userDetails = Get-ADUser $_ -Properties AccountExpirationDate, accountExpires, EmailAddress, Enabled
  
  $userName = $userdetails.Name
  $userEmail = $userdetails.EmailAddress
  Write-Host $userDetails.accountExpires

  If ($userDetails.accountExpires -eq 0 -or $userDetails.accountExpires -eq 9223372036854775807 -or $userDetails.Enabled -eq $false)
  {
   
   $sendEmail = $false
  }
  
  If ($userDetails.AccountExpirationDate -and $userDetails.Enabled -eq $true -and $userDetails.accountExpires -ne 0)
  {
   
   $ExpiryDate = $userDetails.AccountExpirationDate
   
   $ExpiryDate1 = $ExpiryDate.ToShortDateString()
   
   $today = (Get-Date)
   
   $DaysLeft = ($ExpiryDate - $today).days
   
   If ($DaysLeft -le 30 -and $DaysLeft -ge 0)
   {
    $AddBody += "<tr><td>$userName</td> <td><a style='text-decoration:none;color: rgb(0, 0, 0);'>$userEmail</a></td> <td>$ExpiryDate1</td> </tr>";
    $sendEmail = $true
   }
   
  }
 }
 
 If ($sendEmail)
 {
  Write-Output("Sending mail to : " + $ManagerName);
        
  $Body += $AddBody;
  $Body = $Body + "</tbody>
                            </table><br>

                            <p style='font-size:12.0pt;font-family:Arial'>V&auml;nligen meddela oss p&aring; ISS s&aring; snart som m&ouml;jligt genom att svara p&aring; detta mail. Ange om kontona ska f&ouml;rl&auml;ngas 6 m&aring;nader eller avslutas. <br>
       Har du n&aring;gra fr&aring;gor, tveka inte att kontakta oss. <br><br>
       <font color=104160 size=5></font></p>
                            <p style='font-size:12.0pt;font-family:Arial'>Med v&auml;nlig h&auml;lsning<br />
                            ISS
                            </span></b><span style='font-size:12.0pt;font-family:Arial;
                            color: black'><o:p></o:p></span><br />
       <a href='mailto:support.cloud@fiwe.se'><span style='font-size:12.0pt'>support.cloud@fiwe.se</span></a><br><br>
       <img src='http://fiwe.com/signature/v2/img/footer_new.jpg'><br>
       <p style='font-size:6.0pt;font-family:Arial'>Important Note: This e-mail and any attachment thereof are confidential and may contain trade secrets and may also be legally privileged otherwise protected from disclosure. If you have received <br>
       it in error, you are in notice of its status. Please notify us immediately by reply e-mail and then delete this e-mail and any attachment from your system. If you are not the intended recipient please
       <br>understand that you must not copy thise-mail or any attachment or disclose the contents to any other person.
                            
                            
                            </body>  
                            </html>";
   Write-Output($Body);
   $Body > 'file.html'
   send-mailmessage -To $ToEmail -From support.cloud@fiwe.se -Encoding UTF8 -Subject "Användarkonton Fiwe cloud på väg att gå ut, åtgärd krävs." -body $Body -smtpserver 10.122.25.7 -BodyAsHtml -Priority High
  
 }
else{
 "No accounts about to expire." > 'log.csv'
 
 } 
}
}
theduck
  • 2,589
  • 13
  • 17
  • 23
Davoud.Ro
  • 55
  • 4

1 Answers1

0

The problem is caused by setting and resetting sendEmail in a foreach loop.

$_.directReports | ForEach {
    ...
    If ($userDetails.accountExpires -eq 0 -or $userDetails.accountExpires -eq 9223372036854775807 -or $userDetails.Enabled -eq $false) {
        $sendEmail = $false
    }

    If ($userDetails.AccountExpirationDate -and $userDetails.Enabled -eq $true -and $userDetails.accountExpires -ne 0){
        ...
            $sendEmail = $true
    }
}

If ($sendEmail) {

Since the variable is updated multiple times, the final value is set by last iteration. It doesn't matter what values were set on earlier iterations, only the last one is the one that counts.

To fix this, maybe something akin

$AddBody = [string]::Empty # or $AddBody = ""
...
if $AddBody.Length -gt 1 {
    #send email, as $AddBody would contain expiry info
}

would work better. (Back in the days of .Net 1, "" and String::Empty were different things.

vonPryz
  • 22,996
  • 7
  • 54
  • 65
  • @Davoud.Ro Don't change the 1st `$AddBody`, just replace `if($sendEmail)` with the `.Length` test . – vonPryz Oct 07 '19 at 10:13
  • like this do you mean........Instead of IF ($sendEmail) I have to write IF $addBody.length -gt 1 { write-output ("sending mail to" : + $ManagerName); – Davoud.Ro Oct 07 '19 at 11:03