powershell - 如何为即将过期的 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
有人可以帮助我吗?
解决方案
如果用户属性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
,Surname
和UserPrincipalName
. 属性AccountExpirationDate
是accountExpires
转换为本地时间的属性值。
推荐阅读
- javascript - 在类中声明之前调用常规函数与箭头函数
- php - PHP“变量包装器”作为一个数组用于多个数据库的 SQL 查询
- azure - 在单个队列上触发多个函数
- xcode - 如何使用“扩展”在 Xcode 中嵌入自定义编辑器窗口?
- javascript - 尝试在 Node.js 上使用 Sequelize 并遇到创建问题
- list - 使用 Groovy 获得更好的随机值
- couchdb - 如何安装 couchdb 2.3.0 版
- angular - 无法将更新的信息从提供商传递到页面
- c# - 如何动态构建 Func<>?
- mysql - 优化 MySQL CREATE TABLE 查询