Уведомление по электронной почте об истечении срока действия учетной записи Powershell Active Directory для менеджера

У меня есть этот сценарий PowerShell, который отправляет электронные письма менеджерам, если срок действия учетной записи пользователя истекает в течение определенного количества дней, однако менеджеры получают отдельное электронное письмо для каждого пользователя. Есть ли способ отправить только одно письмо со списком пользователей?

      Import-Module ActiveDirectory

#Set our non-changing variables for the email
$From = "accountexpiry@company.com"
$CC = "helpdesk@company.com"
$SMTPServer = "mail.company.com"

#Get the start date, which defaults to today, and the end date which is based off the start date
$startDate = Get-Date
$endDate = $startDate.AddDays(7)

#Query AD for all the accounts between our dates and request for a couple additional properties
$Users = Get-ADUser -Filter {AccountExpirationDate -gt $startDate -and AccountExpirationDate -lt $endDate} -Properties AccountExpirationDate, Manager

#Loop through the query results
Foreach($User in $Users)
{

    #The $User.Manager is not a email address, but a Distinguished Name; to get the email we can pass it to Get-Aduser though
    $Manager = Get-ADUser $User.Manager -Properties EmailAddress

    #Set our dynamic variables
    $To = $Manager.EmailAddress
    $Subject = "Account Expiration Notification for " + $User.Name
    $Body = 
    "Hello,
    This notification is to inform you that the account for $($User.Name) will expire on $($User.AccountExpirationDate). 
    If you need to extend this, please contact HR and IT will process the request.

    Thank you,
    IT Help Desk"

    Send-MailMessage -To $To -From $From -Subject $Subject -SmtpServer $SMTPServer -Body $Body
}

1 ответ

Как предположил @thepip3r в своем комментарии, хорошим способом отправки только одного электронного письма на каждого менеджера может быть использованиеGroup-Object. Код ниже должен помочь, не тестировал его, но я считаю, что он должен работать.

Следует отметить, что этот код предполагает, что всегда существует список пользователей, срок действия которых истекает, и отправляет список пользователей в следующем формате:

Это уведомление информирует вас о том, что срок действия учетной записи для следующих пользователей скоро истечет:
- user.example1 истекает XX / XX / XXXX
- user.example2 истекает XX / XX / XXXX
- user.example3 истекает XX / XX / XXXX

Если вам нужно продлить этот срок, обратитесь в отдел кадров, и ИТ-отдел обработает запрос.

Если вы хотите изменить формулировку электронного письма для случая, когда есть только один пользователь, а когда их несколько, вам следует поработать для этого некоторые условия.

Код

      Import-Module ActiveDirectory

#Set our non-changing variables for the email
$mailProps = @{
    From = "accountexpiry@company.com"
    CC = "helpdesk@company.com"
    SMTPServer = "mail.company.com"
    BodyAsHTML = $true
}

#Get the start date, which defaults to today, and the end date which is based off the start date
$startDate = Get-Date
$endDate = $startDate.AddDays(7)

#Query AD for all the accounts between our dates and request for a couple additional properties
$props = @{
    Filter = "AccountExpirationDate -gt '$startDate' -and AccountExpirationDate -lt '$endDate'"
    Properties = 'AccountExpirationDate', 'Manager'
}
$Users = Get-ADUser @props

# Save the body on a ScriptBlock for later use
$bodyScriptBlock = {
    param([string[]]$UserList)
@"
Hello,
This notification is to inform you that the account for the following users are about to expire:
{0}
If you need to extend this, please contact HR and IT will process the request.

Thank you,
IT Help Desk
"@ -f ($UserList | Out-String)
}

# Group all users by their Manager
$Users | Group-Object Manager | ForEach-Object {
    
    # Get this Manager's email address
    $managerEmail = (Get-ADUser $_.Name -Properties EmailAddress).EmailAddress

    # Create a string[] with the user's Name and their Account's Expiration Date
    $userList = foreach($user in $_.Group)
    {
        '- {0} expires on {1}' -f $user.Name, $user.AccountExpirationDate
    }
    
    # Execute the Body scriptblock passing this user's list
    $body = & $bodyScriptBlock -UserList $userList

    # Set the remaing values for Mail props
    $mailProps.To = $managerEmail
    $mailProps.Subject = "Account Expiration Notification for Managees" # ??? No idea what to put here
    $mailProps.Body = $body

    # Send the email with the list of users
    Send-MailMessage @mailProps
}
Другие вопросы по тегам