查找具有AD属性.whenCreate且少于90天的用户

时间:2018-07-02 18:04:44

标签: powershell

$daysOld = "-90"
$currentDate = get-date
$removeIfBefore = $currentDate.AddDays($daysOld)
$vpnuserstest = Get-ADGroupMember VPN_users -Recursive | select     samaccountname | foreach ($_.samaccountname) {
Get-ADUser $_.samaccountname -Properties samaccountname, whenCreated |
Select-Object samaccountname,@{n='Days Since Created';e={($((Get-Date)) -     $($_.WhenCreated)).Days}} |
Format-table -AutoSize}

详细说明: 我将用户分组VPN_users并搜索其“ samaccountname”和“ whenCreated”属性。然后,我想确定今天的日期并返回90天。任何具有“ whenCreated”日期的人都在那个90天的窗口内,我想添加到表格中以便以后导出。

运行上面的代码时,我会列出所有内容,但是仍然包括“ whenCreated”属性超过90天的所有人。

很抱歉,如果代码看起来像是“弗兰肯斯坦”。。我从不同的Google搜索中提取了不同的方面,并将它们组合在一起。

1 个答案:

答案 0 :(得分:3)

这里是一种方法:构造一个时间戳字符串,并与-LDAPFilter参数一起使用。示例:

$daysOld = 90
$timestampUTC = (Get-Date).AddDays(-$daysOld).ToUniversalTime()
$timestampString = "{0:yyyyMMddHHmmss.0Z}" -f $timestampUTC
Get-ADUser -Properties whenCreated -LDAPFilter "(whenCreated<=$timestampString)"

如果要将结果限制为属于特定组的用户,则可以更新LDAP查询过滤器。示例:

$daysOld = 90
$timestampUTC = (Get-Date).AddDays(-$daysOld).ToUniversalTime()
$timestampString = "{0:yyyyMMddHHmmss.0Z}" -f $timestampUTC
Get-ADUser -Properties whenCreated -LDAPFilter "(&(whenCreated<=$timestampString)(memberOf=CN=Group Name,OU=Container,DC=fabrikam,DC=com))"