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

  1. 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.
  2. Press F5 to run the script
  3. A CSV will be exported to C:\temp\lastlogon.csv containing a list of users and their last logon time. Last Logon Time of local users on server

Was this article helpful?

Related Articles