如果是第 7 天和第 14 天,Send-MailMessage

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

使用下面的代码,当承包商的 AD 帐户在两周内到期时,我可以向特定的人发送电子邮件。我的问题是代码将每天通过任务计划程序触发并每天发送电子邮件。我们是否能够使用 if 语句之类的东西在特定的时间条件下逻辑地采取行动?也许像

if AccountExpirationDate = getdate.adddays(-14) 发送邮件消息
if AccountExpirationDate = getdate.adddays(-7) 发送邮件消息

如果没有,完成此任务的最佳方法是什么?

# 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)
}

是的,你绝对可以用这样的东西来做到这一点:

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

我同意 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)
}