powershell获取aduser特定的日期范围

powershell获取aduser特定的日期范围,powershell,powershell-2.0,powershell-3.0,powershell-4.0,Powershell,Powershell 2.0,Powershell 3.0,Powershell 4.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

您好,感谢您抽出时间阅读本文。 我正在编写一个程序,它将返回特定的日期范围,然后返回我在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年开始收到奇怪的条目,有人看到我的代码有什么奇怪的地方吗?

这里不需要管道-只需使用一点简单的数学,从
字符串
转换为
int
,并按照设计使用
-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
然后使用以下
-Filter
参数调用
Get ADUser

# 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 ))'"

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

您的Where应该比较两个日期,而不仅仅是检查是否有日期。简单的比较不需要{script block},因此
Where Object lastlogondata-gt$desiredDate
我在一个模块中为类似的东西编写了一个自定义实现。根据您的需要,您可能还需要验证提供的一个或多个日期,提供的对象的格式取决于CurrentCultureThank各位,我将使用提供的信息运行回复,看看是否可以获得一些好的数据。不太确定您是想要在最近
n
天登录的用户还是在最近
n
天未登录的用户。我的回答是假设后者,但如果我把你的意图颠倒过来,我可以改变它。doood@LotPings你就是那个人!非常感谢您的帮助。我会将多少天前的
解释为寻找更新的logonData,因此应该
-gt
-ge
完成。简单的开关从
-lt
切换到
-ge
您在哪个版本的powershell中编写了get aduser行?我无法执行此代码我正在进行以下调试:我想我必须导入active directory模块才能正常工作这看起来工作得很好,然而,我需要一个用户指定一个日期范围,当我使用这个线程中的建议调整第一部分时-它不会正确搜索-实际上忘记了这一点-我从2004年得到结果-返回到旧版本的做事,并使用上面发布的bender帮助
 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