0

I want to know which accounts were not connected on AD since 3 months

Here's my code

# connexion ADSI
$objDomaine = [ADSI]’’
$objRecherche = New-Object System.DirectoryServices.DirectorySearcher($objDomaine)
$objRecherche.Filter=’(&(objectCategory=person)(objectClass=user))’

# Fichiers de sortie
$OutFile = "\\xxx\xx\Utilisateurs_inactifs.log"
remove-item $OutFile
ADD-content -path $OutFile -value "LOGIN;CN_COMPLET;LASTLOGON"

foreach ( $ADuser in $objRecherche.FindAll() )
{
    $LastLogon = $ADuser.Properties[’lastlogon’]
    $LastLogon = [int64]::parse($LastLogon)
    $date = (Get-Date -Year 1601 -Month 1 -Day 1 -Hour 0 -Minute 0 -Second 0)
    $date_derniere_connexion = $date.AddTicks($LastLogon)

    #On formatte un peu le tout. On enleve l'heure et on enleve les \, des CNs.
    $DATE_RESULT = $date_derniere_connexion -replace " ..:..:..",""
    $RESULT = "$($ADuser.properties[’samaccountname’]);$($ADuser.path);$($DATE_RESULT)" -replace "\\\,",""
    # On prend la date du jour et on retire 3 mois
    $DATE3MONTHS = (get-date).addmonths(-3).toShortdateString()

    # On test la date (pour enlever les occurences de non-login)
    if ( $DATE_RESULT -ne '01/01/1601' )
        {
        # tester si la date de derniere connexion est plus vieille que 3 mois, si oui on ecrit dans le fichier.
        if ( $DATE_RESULT -lt $DATE3MONTHS )
            { ADD-content -path $OutFile -value $RESULT }
        }
}

In my outfile, I can see many users which last connection is NOT older than 3 months (yesterday!) here's an sample of my outfile

xx;LDAP://CN=xx;15/09/2015
xx;LDAP://CN=xx;09/09/2015
xx;LDAP://CN=xx;16/09/2015
xx;LDAP://CN=xx;07/05/2014
xx;LDAP://CN=xx;16/09/2015
xx;LDAP://CN=xx;09/01/2015

NOTE : My dates are in french version DD/MM/YYYY

Matt
  • 45,022
  • 8
  • 78
  • 119
Alex Lum
  • 175
  • 2
  • 12
  • Do not compare dates as strings, and you should get right results regardless of used locale. – user4003407 Sep 17 '15 at 15:42
  • 1
    If you solved your own question, put the answer in the textbox below. After a day or so click the green checkmark to the left of your answer. Doing that marks the question as solved in the UI. Putting “SOLVED” in the title does not mark the question as solved. – Dour High Arch Sep 17 '15 at 16:09
  • possible duplicate of [Why does PowerShell always use US culture when casting to DateTime?](http://stackoverflow.com/questions/14359053/why-does-powershell-always-use-us-culture-when-casting-to-datetime) – Matt Sep 17 '15 at 18:36

1 Answers1

0
[datetime]::parse("$DATE_RESULT") # this will convert string to date. Parse for my french locale.

Why does PowerShell always use US culture when casting to DateTime?

Matt
  • 45,022
  • 8
  • 78
  • 119
Alex Lum
  • 175
  • 2
  • 12