首页 > 解决方案 > 如何为即将过期的 AD 用户创建警报

问题描述

这是我在 Powershell 中的第一次尝试,我不得不说我不知道​​我在做什么。

所以我想创建一个脚本,当它运行时向管理员发送一封电子邮件,其中包含将在接下来的 30 天内到期的 ADUser 列表。

这是我第一次尝试将用户作为输出,但它不起作用,我不知道为什么不这样做。所以我不能继续做邮件发送的事情。我也没有在互联网上找到类似的东西。

Get-ADUser -Filter 'enabled -eq $true' -SearchBase "CN=Users, DC=mydomain, DC=de" -Properties $var=((get-date).AddDays(30)) -le AccountExpirationDate | Select-Object distinguishedName, AccountExpirationDate

有人可以帮助我吗?

标签: powershellactive-directory

解决方案


如果用户属性accountExpires等于 0 或 9223372036854775807,则帐户永不过期。要获取在特定天数内到期的帐户列表,您可以:

$refDate = (Get-Date).AddDays(30)
$expiringUsers = Get-ADUser -Filter 'Enabled -eq $true' -SearchBase "CN=Users,DC=mydomain,DC=de" -Properties AccountExpirationDate, accountExpires | 
    Where-Object {($_.accountExpires -gt 0 -and $_.accountExpires -ne 9223372036854775807) -and ($_.AccountExpirationDate -le $refDate)} |
    Select-Object Name, DistinguishedName, AccountExpirationDate

接下来,您需要通过电子邮件将其发送给管理员。
当然,有多种方法可以做到这一点,下面的示例将结果作为 CSV 附件发送。

# don't send mail if there are no expiring users found
if ($expiringUsers.Count) {
    # write the results to csv file
    $outFile = Join-Path -Path $env:TEMP -ChildPath ('{0:yyyy-MM-dd}_ExpiringUsers.csv' -f (Get-Date))
    $expiringUsers | Export-Csv -Path $outFile -NoTypeInformation

    # use splatting for cmdlets that take a lot of parameters
    $mailParams = @{ 
        SmtpServer  = 'smtp.fabrikam.com'
        From        = 'troi@fabrikam.com'
        To          = 'admin@fabrikam.com'
        Subject     = 'Expiring user accounts'
        Body        = 'Please find the list of expiring user accounts in the attachment'
        Attachments = $outFile
        # See https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/send-mailmessage
        # for more parameters you might want to use
    } 

    Send-Mailmessage @mailParams
    Write-Host "$($expiringUsers.Count) user accounts are set to expire within the next 30 days. An email has been sent."
}
else {
    Write-Host 'No user accounts are set to expire within the next 30 days'
}

Get-ADUser默认返回以下属性:DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID,SurnameUserPrincipalName. 属性AccountExpirationDateaccountExpires转换为本地时间的属性值。


推荐阅读