Exclusions not working powershell script

Hello,

I am using a script that goes out and grabs the user accounts that have been inactive for 45 days or more. Some domains it works like it should giving me the correct output and in some domains it gives me the 45 and less days output. I really need help getting this script accurate.

$CurrentDate = Get-Date
$NumberDays = 45
$userCollection = Search-ADAccount -AccountInactive -UsersOnly -Server local.domain.com -SearchBase "DC=local,DC=domain,DC=com"
$userCollection | Get-ADUser -Properties * | Select-Object Name,Office,DistinguishedName,LastLogonDate,Enabled,@{n="Days";e={((Get-Date) - $_.LastLogonDate).Days}},@{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}}

Name                        Office            LastLogonDate                        Enabled Days
----                            ------              -------------                               -------     ----
Shepaum, Lillian       Boca Raton    10/11/2013 10:20:02 AM       True        96
Davis, Graylon          Waynesboro  11/11/2013 2:01:50 PM         True        65
Murphy, Ellen           Boca Raton                                                   True     
Keller, Loretta          Neosho         11/25/2013 1:40:23 PM          True        51
Lackey, J.R.              McMinnville    12/10/2013 1:02:22 PM          True        36
Neuendorf, Tim        McMinnville    12/3/2013 8:16:53 AM            True        44
Roy, Kelli                  Bentonville    12/2/2013 2:35:25 PM            True        44
Fristoe, Aaron          Bentonville    12/2/2013 1:21:01 PM            True        44


  • Edited by Aaron Berry Thursday, January 16, 2014 3:01 PM
January 16th, 2014 6:00pm

LastLogonDate and LastLogon are different properties, don't mix them up like that.  LastLogonDate is corresponds to the LDAP property lastLogonTimestamp, which is replicated to all DCs.  LastLogon is a more precise value, but is not replicated to other domain controllers.

For most purposes related to inactive accounts, you can just use LastLogonDate and pretend that LastLogon doesn't exist.

Edit:  Also, you don't seem to be using your $NumberDays variable anywhere.  You need to specify either the DateTime or Timespan parameters to Search-ADAccount, for example:

$CurrentDate = Get-Date
$NumberDays = 45

Search-ADAccount -AccountInactive -UsersOnly -DateTime ($CurrentDate.AddDays(-$NumberDays))

  • Edited by David Wyatt Thursday, January 16, 2014 3:10 PM
  • Proposed as answer by Mike Laughlin Thursday, January 16, 2014 5:08 PM
Free Windows Admin Tool Kit Click here and download it now
January 16th, 2014 6:05pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics