Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last logon time,computer and username together with Powershell

I have a script which gets the last logon times of each computer in the domain.

My script:

$dcs = Get-ADComputer -Filter { OperatingSystem -NotLike '*Server*' } -Properties OperatingSystem

foreach($dc in $dcs) { 
    Get-ADComputer $dc.Name -Properties lastlogontimestamp | 
    Select-Object @{n="Computer";e={$_.Name}}, @{Name="Lastlogon"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}}
}

Result:

Computer    Lastlogon                                                            
--------    ---------                                                            
DC1         6/06/2013 16:38:24                                                   
DC2         6/06/2013 16:30:40 

I also want to get who/which account made this logon. For example:

Computer    Lastlogon            User                                                   
--------    ------------------   ----                                                         
DC1         6/06/2013 16:38:24   user2                                                
DC2         6/06/2013 16:30:40   user1

How should I edit my script to get the logged usernames also?

like image 646
Korki Korkig Avatar asked Dec 28 '25 10:12

Korki Korkig


1 Answers

How about Event logs:

$dcname = $dc.name

$lastevent = get-winevent -FilterHashtable @{LogName="security"; ID=4624} -computername $dcname | select -first 1

That will get you the most recent logon event - you will have to work from there to pull the user name from the message, which could be tricky, but there are probably several ways. Pull the string between "Account Name:" and "Account Domain:" from $lastevent.message.

Also need a way to filter out SYSTEM and non-user accounts. Computer accounts will end with $.

like image 119
Gary S Avatar answered Dec 31 '25 05:12

Gary S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!