Search code examples
powershellemailgetdate

If 7th day and 14th day, Send-MailMessage


Using the code below I'm able to email a specific person when a contractor's AD account is within two weeks of expiring. My issue is the code will trigger daily via Task Scheduler and send the email every day. Are we able to use something like an if statement to logically act on specific timing conditions? Perhaps something like

if AccountExpirationDate = getdate.adddays(-14) send-mailmessage
if AccountExpirationDate = getdate.adddays(-7) send-mailmessage

If not, what would be the best way to get this done?

# List every active account with a "SACRequest Account" desctription that will expire in 14 days and inlcude the name and email address of the original account requester (extensionAttribute1,extensionAttribute2)
Import-Module ActiveDirectory
$Today = Get-Date
$Expires = $Today.AddDays(14) 
$reportObject = @()
$userList = Get-ADUser -Filter {Description -like "SACRequest Account" -and Enabled -eq $True} -Properties displayname, accountExpires, description, passwordexpired,"msDS-UserPasswordExpiryTimeComputed",enabled,AccountExpirationDate,LastLogonDate,logoncount,passwordlastset, badlogoncount,lastbadpasswordattempt,extensionAttribute1,extensionAttribute2,department |
    select displayname, accountExpires, description, passwordexpired,"msDS-UserPasswordExpiryTimeComputed",enabled,AccountExpirationDate,LastLogonDate,logoncount,passwordlastset, badlogoncount,lastbadpasswordattempt,extensionAttribute1,extensionAttribute2,department |
    Where-Object {$_.accountExpires -ne $NeverExpires  -and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -ne $Expires}
    Sort-Object msDS-UserPasswordExpiryTimeComputed -Descending
$obj = New-Object PSObject
foreach ($user in $userList) {
    # SPLAT
    $obj = New-Object PSObject
    $obj | Add-Member NoteProperty Name($user.displayname)
    $obj | Add-Member NoteProperty Description($user.description)
    $obj | Add-Member NoteProperty 'Password Expired'($user.Passwordexpired)
    $obj | Add-Member NoteProperty 'Account is Enabled'($user.Enabled)
    $obj | Add-Member NoteProperty 'AccountExpirationDate'($user.AccountExpirationDate.ToString('MM-dd-yyyy'))
    $obj | Add-Member NoteProperty 'LastLogonDate'($user.LastLogonDate.ToString('MM-dd-yyyy'))
    $obj | Add-Member NoteProperty 'Password Last Set'($user.PasswordLastSet)   
    $obj | Add-Member NoteProperty 'Failed Logon Attempt'($user.lastbadpasswordattempt) 
    $obj | Add-Member NoteProperty 'TotalLogonCount'($user.logoncount)
    $obj | Add-Member NoteProperty 'Total Failed Logons'($user.badlogoncount)
    $obj | Add-Member NoteProperty 'SACSubmitter'($user.extensionAttribute1)
    $obj | Add-Member NoteProperty 'SACSubmitterEmail'($user.extensionAttribute2)
    $obj | Add-Member NoteProperty 'Department'($user.department)
    #$obj | Add-Member NoteProperty 'Password Expiration Date'($outputexp.ToString('MM-dd-yyyy'))
    $reportObject += $obj
}
# Export CSV containing all SACR accounts expiring soon.
$reportObject | Export-Csv -Path \\intranet\c$\IT\SystemAccessControlRequestForm\SACRAccountsExpiringSoon.csv -NoTypeInformation
# Send email notification to system administrators.
Send-MailMessage -From [email protected] -To [email protected] -Subject "New System Access Control Request Export" -body "New System Access Control Request Export can be found here file://///intranet/c$/IT/SystemAccessRequestForm/"  -SmtpServer mail.organization.org
# Send email notification to original submitter
$from    =  "Your Friends in IT <[email protected]>"
$subject =  "Your contractors's login account will expire soon!"      
$csv = Import-Csv -Path "\\intranet\c$\IT\SystemAccessControlRequestForm\SACRAccountsExpiringSoon.csv"
foreach ($user in $csv) {
    $Name = $user.name
    $to = $user.SACSubmitterEmail
    $hello = $user.SACSubmitter
    #$AccountExpirationDate.ToString("MM/dd/yyyy")
    $AccountExpirationDate = $user.AccountExpirationDate # -as [DateTime]
    $TotalLogonCount = $user.TotalLogonCount
    $LastLogonDate = $user.LastLogonDate
    $body =  "Hello $hello,<br><br>"
    $body +=  "The login account you requested for <b>$Name</b> is set to expire on <b> $AccountExpirationDate</b>.<br><br>"
    $body +=  "$name logged onto our systems a total of <b>$TotalLogonCount</b> times with the last successful log in posted on <b> $LastLogonDate</b>.<br><br>"
    $body +=  "<a href='http://intranet/Intranet/forms/viewform.cfm?formid=154'>If this account needs to remain active please submit a new System Access Control Request by clicking here.</a><br><br>"
    $body +=  "Kind Regards,<br>"
    $body +=  "Your friends in IT"
    $mail = New-Object System.Net.Mail.Mailmessage $from, $to, $subject, $body
    $mail.IsBodyHTML=$true
    $server = "mail.organization.org"
    $port   = 25
    $Smtp = New-Object System.Net.Mail.SMTPClient $server,$port
    $Smtp.Credentials = [system.Net.CredentialCache]::DefaultNetworkCredentials
    $smtp.Send($mail)
}

Solution

  • Yes, you can definitely do that with some like this:

    $Today = Get-Date -Format 'MM-dd-yyy'
    foreach ($user in $csv) {
      if (([datetime]$user.AccountExpirationDate).AddDays(-14) -eq $Today) {
        #send the report
      }
    }