Check a User's Last Login in with PowerShell | Export to CSV

By Mark D. Albin, MS

Last Login in Active Directory

To search the entire domain for a user's last login in Active Directory using PowerShell, you can use the Get-ADUser cmdlet with the -Filter parameter.

                         
Get-ADUser -Filter {SamAccountName -eq "username"} -Properties lastLogon | Select-Object Name, SamAccountName, @{Name="LastLogon"; Expression={[DateTime]::FromFileTime($_.lastLogon)}} | Export-CSV -Path "user_last_login.csv" -NoTypeInformation 
                

This PowerShell code retrieves the last logon information for a user account in Active Directory and exports the result to a CSV file.

The Get-ADUser cmdlet with the -Filter parameter is used to search for a user with a specific SamAccountName in Active Directory. The lastLogon attribute is then retrieved using the -Properties parameter.

The results are then piped to the Select-Object cmdlet, which is used to display only the Name, SamAccountName, and LastLogon properties of the user object. The LastLogon property is converted to a human-readable format using the [DateTime]::FromFileTime() method.

Finally, the Export-CSV cmdlet is used to export the search results to a CSV file named "user_last_login.csv" in the current directory. The -NoTypeInformation parameter is used to exclude the type information from the CSV file.

Check a User's Last Login in with PowerShell | Export to CSV

When using any software or code, it is important to remember that there is always a certain level of risk involved. As a user, you are responsible for ensuring that the software or code you are using is suitable for your needs, and that you are aware of any potential risks associated with its use.

If you are considering using any code or software provided by ITMS, we advise you to review our terms of service webpage at https://www.itms-us.com/Website-Terms-Of-Use. This webpage outlines the terms and conditions that govern your use of our website and any services or products that we provide.

Additionally, please note that any code or software provided by ITMS is provided "as is," without any warranties or guarantees. While we strive to provide high-quality code and software that is free from defects, we cannot guarantee that our code or software will meet your specific needs or operate error-free.

Ultimately, the decision to use any code or software provided by ITMS is yours alone. By using our code or software, you acknowledge and accept the risks associated with its use and agree to hold ITMS harmless for any damages or losses that may result from its use.