Если 7-й день и 14-й день, Send-MailMessage - PullRequest
0 голосов
/ 17 октября 2019

Используя приведенный ниже код, я могу отправить электронное письмо конкретному лицу, когда срок действия учетной записи подрядчика в AD истекает через две недели. Моя проблема в том, что код будет запускаться ежедневно через планировщик задач и отправлять электронную почту каждый день. Можем ли мы использовать что-то вроде оператора if, чтобы логически действовать в определенных временных условиях? Возможно что-то вроде

, если AccountExpirationDate = getdate.adddays (-14) send-mailmessage
if AccountExpirationDate = getdate.adddays (-7) send-mailmessage

Если нет, то как лучше всего это сделать?

# 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 ncaban@organization.org -To ncaban@organization.org -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 <systems@organization.org>"
$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)
}

Ответы [ 2 ]

1 голос
/ 17 октября 2019

Я согласен с vonPryz в том, что вы должны запланировать этот еженедельный график.

Что касается вашего сценария, я думаю, что это можно сделать с небольшой уборкой. Во-первых, ваша переменная $NeverExpires никогда не определяется, когда вы комментируете # SPLAT, а не брызги, плюс вы создаете файл CSV из массива объектов, а затем снова импортируете этот файл CSV, пока у вас все еще есть $reportObject.

Может быть, что-то вроде ниже будет более удобным для обслуживания:

# List every active account with a "SACRequest Account" desctription that will expire within 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) 
$properties = 'DisplayName', 'accountExpires', 'AccountExpirationDate', 'Description', 'PasswordExpired', 'msDS-UserPasswordExpiryTimeComputed',
              'Enabled', 'LastLogonDate', 'logonCount', 'passwordlastset', 'BadLogonCount', 'LastBadPasswordAttempt', 
              'extensionAttribute1', 'extensionAttribute2', 'Department'
$filter     = "Description -like '*SACRequest Account*' -and Enabled -eq 'True' -and PasswordNeverExpires -eq 'False' -and PasswordNotRequired -eq 'False'"

$userList   = Get-ADUser -Filter $filter -Properties $properties | 
              Where-Object {$_.accountExpires -ne 0 -and $_.accountExpires -ne 9223372036854775807 -and $_.AccountExpirationDate -ge $Expires} |
              Sort-Object -Poperty 'msDS-UserPasswordExpiryTimeComputed' -Descending

$reportObject = foreach ($user in $userList) {
    $pwExpiresAt = [datetime]::FromFileTime($user."msDS-UserPasswordExpiryTimeComputed")
    [PsCustomObject]@{
        'Name'                     = $user.DisplayName
        'Description'              = $user.Description
        'Password Expired'         = $user.PasswordExpired
        'Password Expiration Date' = $pwExpiresAt.ToString('MM-dd-yyyy')
        'Account is Enabled'       = $user.Enabled
        'AccountExpirationDate'    = $user.AccountExpirationDate.ToString('MM-dd-yyyy')
        'LastLogonDate'            = $user.LastLogonDate.ToString('MM-dd-yyyy')
        'Password Last Set'        = $user.PasswordLastSet
        'Failed Logon Attempt'     = $user.LastBadPasswordAttempt
        'TotalLogonCount'          = $user.logonCount
        'Total Failed Logons'      = $user.BadLogonCount
        'SACSubmitter'             = $user.extensionAttribute1
        'SACSubmitterEmail'        = $user.extensionAttribute2
        'Department'               = $user.Department
    }
}

# 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.
# splat
$mailParams = @{
     'From'       = 'ncaban@organization.org'
     'To'         = 'ncaban@organization.org'
     '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-MailMessage @mailParams

# Send email notification to original submitter
# Any reason why you do not use Send-MailMessage here?
$from    =  "Your Friends in IT <systems@organization.org>"
$subject =  "Your contractors's login account will expire soon!"      
$reportObject | ForEach-Object {
    $name  = $_.Name
    $to    = $_.SACSubmitterEmail
    $hello = $_.SACSubmitter
    $AccountExpirationDate = $_.AccountExpirationDate
    $TotalLogonCount = $_.TotalLogonCount
    $LastLogonDate = $_.LastLogonDate
    # a Here-String is used for the HTML body
    $body =  @"
Hello $hello,<br><br>
The login account you requested for <b>$name</b> is set to expire on <b>$AccountExpirationDate</b>.<br><br>
$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>
<a href='http://intranet/Intranet/forms/viewform.cfm?formid=154'><br><br>
If this account needs to remain active please submit a new System Access Control Request by clicking here.</a><br><br>
Kind Regards,<br>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)
}
0 голосов
/ 17 октября 2019

Да, вы определенно можете сделать это с некоторыми подобными способами:

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