Top

Get Last Logged in User Using Powershell

Ever needed to get the last logged in user on a Windows workstation? Here's how to do it in Powershell.

Get the last logged-in user on a Windows workstation using Powershell

It’s happened to all of us system administrators at some point. We need to track down the last logged-in user on a specific workstation. Maybe they messed up and maybe your organization holds people accountable for the things they do on company devices. Either way, here’s a couple one-liners that will get the information you need fast.

Using the ntuser.dat file

Get-ChildItem C:\users\*\ntuser.dat -Force | Select @{Name = 'User'; Expression={Split-Path $PSItem.DirectoryName -Leaf}}, Last* | Sort LastWriteTime | Select -Last 1

Using the ntuser policy file: More accurate using but will include generics as well if no one logged on before…

Get-ChildItem C:\users\*\ntuser.pol -Force | Select @{Name = 'User'; Expression={Split-Path $PSItem.DirectoryName -Leaf}}, Last* | Sort LastWriteTime | Select -Last 1

Using a local file of workstations to run it against

$devices    = Import-Csv AD_Devices.csv
$collection = @()
foreach ($dev in $devices) {
    if (-Not (Test-Connection -Count 2 $dev.Name -ErrorAction SilentlyContinue)) {    
        continue    
    }    
    $session = New-PSSession $dev.Name -ErrorAction SilentlyContinue    
    if (-Not $session) {    
        continue    
    }    
    Write-Host $dev.Name" established session!" -ForegroundColor Green    
    $obj = New-Object PSObject    
    $obj | Add-Member NoteProperty Name($dev.Name)    
    $users = Invoke-Command -Session $session -ScriptBlock {    
        $account = Get-ChildItem C:\users\*\ntuser.pol -Force | Select @{Name = 'User'; Expression={Split-Path $PSItem.DirectoryName -Leaf}}, Last* | Sort LastWriteTime | Select -Last 1    
        if ($account.User -eq "All Users") {    
            $account = Get-ChildItem C:\users\*\ntuser.dat -Force | Select @{Name = 'User'; Expression={Split-Path $PSItem.DirectoryName -Leaf}}, Last* | Sort LastWriteTime | Select -Last 1    
        }    
        return ($account.User, $account.LastWriteTime)    
    }
    $obj | Add-Member NoteProperty AccountName($users[0])
    $obj | Add-Member NoteProperty LastWriteTime($users[1])
    $collection += $obj
}

$collection | Export-CSV -NoTypeInformation AD_Device_UserLogons.csv

As usual, there’s always more than one way to automate something and every solution is specific to your environment. Use this as a starting point to get the wheels turning! Hope it helps!

Think I might be a good fit for your project?

Let's get the conversation started!