PowerShell script showing all login sessions of users for the last month

Hello,

As it wrote in the title, I need a script that will show me all login in the Domain.

i got something but its showing me a generic date and time, Also i need to export it to csv file.

Get-ADUser -Filter {enabled -eq $true} -Properties LastLogonTimeStamp |
Select-Object Name,@{n=‘LastLogon’;e={[DateTime]::FromFileTime($_.LastLogon)}} | Export-Csv c:\public\logon30days.csv -NoTypeInformation

what im missing?

 

Thx for the help!

 

This is because your output property set from Get-ADUser does not contain LastLogon. You must include it with the -Properties parameter:

 

Get-ADUser -Filter {enabled -eq $true} -Properties LastLogon

thanks for answer,

when i use your line code, I get the real login of the users that i have entered with, but all users that i havent log in with i get srtrange date and time.
how do i changing it? i want to see the date and time i have created them.
if you asking yourself, i got a project in MCSA course.

thanks again.

 

.Selfridge 12/31/1600 4:00:00 PM
David.Sehmi 12/31/1600 4:00:00 PM
David.Sebastian 12/31/1600 4:00:00 PM
David.Searle 12/31/1600 4:00:00 PM
David.Scriven 12/31/1600 4:00:00 PM
 

Display all properties so you can see what you specifically need:

Get-ADUser -Filter {enabled -eq $true} -Properties *

You are seeing this issue for users who have never logged on. You will need logic to handle that situation. You can check that LastLogon contains a convertible [datetime]format.

Get-ADUser -Filter 'enabled -eq $true' -Properties LastLogon |
    Select-Object Name,@{n=’LastLogon’;e={if ($_.LastLogon) { [DateTime]::FromFileTime($_.LastLogon) } else { "" }}} |
        Export-Csv c:\public\logon30days.csv -NoTypeInformation

You can run the following to reproduce your issue:

[datetime]::FromFileTime('')

If you want to substitute the user creation date for when LastLogon is blank, you can output that in your else condition:

Get-ADUser -Filter 'enabled -eq $true' -Properties LastLogon,WhenCreated |
    Select-Object Name,@{n=’LastLogon’;e={if ($_.LastLogon) { [DateTime]::FromFileTime($_.LastLogon) } else { $_.WhenCreated }}} |
        Export-Csv c:\public\logon30days.csv -NoTypeInformation

Still showing me the generic time and date.

if i want to see only the users who logged in. wat i need to change in the code?

You should be able to use the filter where lastlogon like * to find all non-null lastlogon values:

Get-ADUser -Filter '(enabled -eq $true) -and (lastlogon -like "*")'