Reputation: 491
I am trying to pull list of the users from specific OU if LastLogon is greater 60 days from today. Here is the script but it seems not working as expected.
Get-ADUser -filter {Enabled -eq 'True'} -SearchBase $OU -Properties * | Select UserPrincipalName, mail, LastLogon, Enabled | Where-Object {{$_.LastLogon -lt (Get-Date).AddDays(-60).ToFileTime().toString()}} #| ConvertTo-Json
Not able filter the data based on date condition. Please help.
I tried below script at suggested by Abraham
(Get-ADUser -filter {Enabled -eq 'True'} -SearchBase $OU -Properties * | Select UserPrincipalName, mail, LastLogon, Enabled).where{$_.LastLogon -lt (Get-Date).AddDays(-60)} #| ConvertTo-Json
Response: Error
Could not compare \"132629184515770181\" to \"06/07/2021 22:21:36\". Error: \"C
annot convert value \"6/7/2021 10:21:36 PM\" to type \"System.Int64\". Error: \"Invalid cast f
rom \u0027DateTime\u0027 to \u0027Int64\u0027.\"\"
Upvotes: 2
Views: 455
Reputation: 61093
Try with this, my advice, don't call all properties -Properties *
, only those you need to query and LDAP query is a lot faster than filtering with Where-Object
or .Where()
method.
$limitDate = [datetime]::Now.AddMonths(-2).ToFileTime()
$params = @{
LDAPFilter = "(&(!userAccountControl:1.2.840.113556.1.4.803:=2)(lastLogonTimestamp>=$limitDate))"
SearchBase = $OU
Properties = 'mail', 'LastLogonDate'
}
Get-ADUser @params |
Select-Object UserPrincipalName, mail, LastLogonDate, Enabled
Upvotes: 2