Power Shell to report Last Logon activity.

Hi,

I am using  following  PS script to get report of last logon  

Get-ADUser -Filter * -SearchBase "dc=<domain>,dc=<local>" -ResultPageSize 0 -Prop CN,samaccountname,lastLogonTimestamp | Select CN,samaccountname,@{n="lastLogonDate";e={[datetime]::FromFileTime  
($_.lastLogonTimestamp)}} | Export-CSV -NoType <filepath>\<filename.csv>
 
The script run fins  but  result of Time and date  is coming up like this (  static datetime FromFileTime(long fileTime) 127789413286274687 )

Tried different script and method to over come this but I am not getting reqruied result.

Can any one help on this to  genrate report for user when last  logon ( days90 ).

Thanks

Regards
Asif
Asif NaeemSr. System Administrator ( Wintel & UNIX (AIX) Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

McKnifeCommented:
https://gallery.technet.microsoft.com/scriptcenter/Get-Active-Directory-user-246f17c7 is a MS script gallery entry for you.
Please say whether it helps or what exactly you need concerning your 90 days. Would you like to list stale accounts (not used for 90 days)? Simply goole "powershell list stale accounts".
0
Tom CieslikIT EngineerCommented:
It was part of discussion on EE some time ago.

I got script that will show you all users logon to let say 90 days ago.
You can change this parameter, just replace number 90 with number days back you want.

Remember to replace domain name with yours and run script on DC as administrator.
Result will be stored in c:\temp\OLD_User.csv, but also you can change that. If you not, make sure TEMP is a directory on your C drive on DC.


import-module activedirectory  
$domain = "YourDomain.local"  
$DaysInactive = 90  
$time = (Get-Date).Adddays(-($DaysInactive)) 
  
# Get all AD User with lastLogonTimestamp less than our time and set to enable 
Get-ADUser -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties LastLogonTimeStamp | 
  
# Output Name and lastLogonTimestamp into CSV  
select-object Name,@{Name="Stamp"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp).ToString('yyyy-MM-dd_hh:mm:ss')}} | export-csv c:\temp\OLD_User.csv -notypeinformation

Open in new window

0
MichelangeloSystem Administrator / PostmasterCommented:
Hi, some background to double check wether what you are expecting from that attribute is what it really does or not, and some tentative ways do identify stale accounts:

LastLogonTimestamp

It is important to note that the intended purpose of the lastLogontimeStamp attribute to help identify inactive computer and user accounts. The lastLogon attribute is not designed to provide real time logon information. With default settings in place the lastLogontimeStamp will be 9-14 days behind the current date.
[...]
To verify if the lastLogonTime stamp is being updated and replicated as expected you can use repadmin.exe with the showattr switch. Some examples are given below. These examples are intended to demonstrate that lastLogontimeStamp is being updated within the window of 9-14 days and replicated to all DC’s in the domain. They are not an example of how to manage stale accounts.

1. Using repadmin to check the value of lastLogontimeStamp on all DC’s in a domain for one user:
repadmin /showattr * (DN of the target user) /attrs:lastLogontimeStamp >lastLogontimeStamp.txt
Example:
repadmin /showattr * CN=user1,OU=accounting,DC=domain,dc=com /attrs:lastLogontimeStamp >lastLogontimeStamp.txt
2. Using repadmin to dump the lastLogontimeStamp for all users in a domain including users that have no data in the lastLogontimeStamp attribute:
repadmin /showattr * /subtree /filter:”(&(objectCategory=Person)(objectClass=user))” /attrs:lastLogontimeStamp >lastLogontimeStamp.txt
3. Dump lastLogonTime stamp for users but only ones that have the attribute populated
repadmin /showattr * dc=domain,dc=com /subtree /filter:”((&(lastLogontimeStamp=*)(objectCategory=Person)(objectClass=user)))” /attrs:lastLogontimeStamp > lastLogontimeStamp-2-22-2009.txt
from https://blogs.technet.microsoft.com/askds/2009/04/15/the-lastlogontimestamp-attribute-what-it-was-designed-for-and-how-it-works/

LastLogon attribute

This attribute is not replicated and is maintained separately on each domain controller in the domain. To get an accurate value for the user's last logon in the domain, the Last-Logon attribute for the user must be retrieved from every domain controller in the domain. The largest value that is retrieved is the true last logon time for that user.
from https://docs.microsoft.com/en-us/windows/desktop/adschema/a-lastlogon

Here some code to perform check for a user,
# check logon on all DCs
$myuser = "mysuer"
$mydomain = "mydomain"
$AllDCdom = Get-ADDomainController  -filter { name -like "*"} -Server $mydomain
$AllDCdoms | Select-Object -expandproperty hostname | ForEach-Object {
    get-aduser $myuser -Properties lastlogon,lastlogontimestamp, lastlogondate -server $_
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
The Ultimate Tool Kit for Technolgy Solution Provi

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy for valuable how-to assets including sample agreements, checklists, flowcharts, and more!

Philip ElderTechnical Architect - HA/Compute/StorageCommented:
We use the following to track user logons in our various managed environments:
# ============================================================================================== 
#   
# Script Name: get User and last logon time into a CSV file 
#  
# AUTHOR: Mohamed Garrana ,  
# DATE  : 4/13/2010 
#  
# COMMENT:  2016-05-12 MPECS Version.
#  
# ============================================================================================== 
 
function connect{ 
 
$ADpath = "LDAP://OU=CLI-Users,OU=CLI-Hosting,DC=CLI,DC=LAN" #set your ldap path to your domain or certian OU  
$searcher = New-Object DirectoryServices.DirectorySearcher 
$RootSearch = New-Object directoryservices.directoryentry $ADpath 
$searcher.searchroot = $RootSearch 
$searcher.filter = "(objectClass=user)" 
$allusers = $searcher.findall() 
foreach ($user in $allusers) { get-lastlogontime }     
} 
function get-lastlogontime { 
    BEGIN { } 
    PROCESS  { 
    #Write-Host $user.Properties.Displayname[0] 
    try { 
    $name = $user.Properties.displayname[0]  
    $adlastlogon=$user.Properties.lastlogon[0]
    $principalname=$user.Properties.principalname[0] 
    } 
    Catch { 
    Write-Host -ForegroundColor Red "   <<< WHoops ... >>>  $name : Error reading a required property from the AD User object, execution will continue anyway ;)" 
        continue 
        } 
    finally { 
    [datetime]$initialdate="1601/01/01" #microsoft date used to calculate lastlogon 
    $lastlogon = $initialdate.Addseconds(($adlastlogon*1e-7)) #nano seconds interval + initial date 
    $AdUser = New-Object psobject  
    $AdUser | Add-Member NoteProperty DisplayName ($name) 
    $AdUser | Add-Member NoteProperty LastLogon ($lastlogon) 
    $AdUser | Add-Member NoteProperty PrincipalName ($principalname)
    Write-Output $AdUser 
    } 
    }  
    END{} 
} 
$csvfile="C:\Temp\UserLastLogon.csv" #set the location of your output file 
connect |  Export-Csv $csvfile 

Open in new window

VARIABLES to set:
 * LDAP path
 * Make sure C:\Temp exists
 * Run in an ELEVATED PowerShell session
0
MichelangeloSystem Administrator / PostmasterCommented:
the above script has the limit described above: LastLogon is not replicated to all DCs so you may get an outdated result.
Again, check here
LastLogon attribute
This attribute is not replicated and is maintained separately on each domain controller in the domain. To get an accurate value for the user's last logon in the domain, the Last-Logon attribute for the user must be retrieved from every domain controller in the domain. The largest value that is retrieved is the true last logon time for that user.
from https://docs.microsoft.com/en-us/windows/desktop/adschema/a-lastlogon
0
Peter GreggProduct SpecialistCommented:
Check this earlier thread:  https://www.experts-exchange.com/questions/29108678/How-to-create-reports-for-inactive-users-devices-and-mailboxes.html

Powershell to find inactive accounts Active Directory for 90 days or longer.

Search-ADAccount -UsersOnly -AccountInactive -TimeSpan 90 | ?{$_.enabled -eq $True} | Get-ADUser -Properties Name, EmailAddress, Department, Description, lastLogonTimestamp | Select Name, EmailAddress, Department, Description,@{n='lastLogonTimestamp';e={[DateTime]::FromFileTime($_.lastLogonTimestamp)}} | Export-Csv D:\temp\testfunytest.csv

Source: http://expert-advice.org/active-directory/powershell-to-find-inactive-ad-users-and-computers-accounts/
0
Asif NaeemSr. System Administrator ( Wintel & UNIX (AIX) Author Commented:
Thanks everyone.
0
McKnifeCommented:
Asif, it would be nice to hear some feedback why one single suggestion helped and the others did not. Everyone can only learn from it.
0
Tom CieslikIT EngineerCommented:
I have objection too
The question was:

Can any one help on this to  genrate report for user when last  logon ( days90 ).

I don't understand why Michelangelo's post was awarded

According to question his post is not the best solution
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.