Export last login time of local users to a CSV
This can be a handy script to find out which users are still active on a server before you set them up on a new server, or remove them from your current server.
This script is intended for servers or computers that are not connected to a domain, as it only collects the last logon times of local users.
Make sure you have a temp folder located at C:\temp to export your CSV to.
$users = Get-WmiObject -Class Win32_UserAccount -Filter "LocalAccount='True'" $CSVpath = "C:\temp\lastlogon.csv" foreach($user in $users){ $lastlogonstring = (net user $user.Name | findstr /B /C:"Last logon").trim("Last logon ") $lastlogonstring $lastlogonproperties = @{ Username = $user.Name LastLogon = $lastlogonstring } $forcsv = New-Object psobject -Property $lastlogonproperties $forcsv | export-Csv $CSVpath -Append -NoTypeInformation }
How to run the script
- Copy and paste the above script into PowerShell ISE or Visual Studio Code. If using Visual Studio Code, be sure to save it as a PowerShell file first so that you can run it.
- Press F5 to run the script
- A CSV will be exported to C:\temp\lastlogon.csv containing a list of users and their last logon time.
Leave a Reply
Want to join the discussion?Feel free to contribute!