Powershell get-aduser特定日期范围

时间:2018-07-06 20:41:58

标签: powershell powershell-v2.0 powershell-v3.0 powershell-v4.0

您好,谢谢您抽出宝贵的时间阅读本文。 我正在编写一个程序,该程序将回顾特定日期范围,然后返回我在get-aduser cmdlet中指定的值

到目前为止,我的代码在这里:

    $grabDate = Read-Host 'enter how many days back you want to search'
$date = Get-Date
$desiredDate = $date.AddDays(- $grabDate)
Write-Host $desiredDate 'to' $date 'is your search range'
Pause

Get-ADUser -Filter * -Properties Name, LastLogonDate | Where-Object { $date.AddDays(- $grabDate) } | Select-Object name, LastLogonDate

我知道这不是最干净的代码,我主要关注一些多余的步骤:

Get-ADUser -Filter * -Properties Name, LastLogonDate | Where-Object { $date.AddDays(- $grabDate) } | Select-Object name, LastLogonDate

当我输入30天进行搜索时,我收到2016年的奇怪记录,有人看到我的代码有什么奇怪之处吗?

2 个答案:

答案 0 :(得分:1)

这里不需要管道-只需使用一些简单的数学运算,从stringint的转换,并使用设计时使用的-Filter参数。

像这样设置$grabDate,这样您将获得实际的int值,而不是字符串

# Convert Read-Host input to an integer, and multiply by -1 to get the negative value
$grabDate = [Convert]::ToInt32( (Read-Host 'enter how many days back you want to search' ) ) * -1

然后使用以下Get-ADUser参数调用-Filter

# Use the filter to return only the users who haven't logged on in the
# last $grabDate days
Get-ADUser -Filter "LastLogonDate -ge '$((Get-Date).AddDays( $grabDate ))'"

这样,您只需返回您关心的ADUser,而不必再次处理用户列表。使用-Filter *可能是一项昂贵的操作,尤其是在较大的AD环境中。

答案 1 :(得分:0)

 Import-Module ActiveDirectory

# Set the number of days since last logon
$DaysInactive = 90
$InactiveDate = (Get-Date).Adddays(-($DaysInactive))

#-------------------------------
# FIND INACTIVE USERS
#-------------------------------
# Below are four options to find inactive users. Select the one that is most appropriate for your requirements:

# Get AD Users that haven't logged on in xx days
$Users = Get-ADUser -Filter { LastLogonDate -lt $InactiveDate -and Enabled -eq $true } -Properties LastLogonDate | Select-Object @{ Name="Username"; Expression={$_.SamAccountName} }, Name, LastLogonDate, DistinguishedName