On a large network where people often shares one computer, it could be useful to know who is the last person who logged on a certain computer.
Like much other information, the log-on user’s information is stored in the registry. You can check them out in the following location in the RegEditor app.
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI

Obviously, navigating through the registry isn’t an effective way to begin with, not to mention that you will need to access it through a remote computer.
Get-ItermProperty is a very useful PowerShell cmdlet that lets you retrieve information from your registry effectively.
$regpath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI'
$regvalue = Get-ItemProperty -Path $regpath
$regvalue.LastLoggedOnUser
$regvalue.LastLoggedOnDisplayName
To get the information from a remote computer, wrap it up in a Invoke-Command cmdlet.
$computer = Read-Host 'Computer'
Invoke-Command -ComputerName $computer -ScriptBlock {
$regpath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI'
$regvalue = Get-ItemProperty -Path $regpath
$regvalue.LastLoggedOnUser
$regvalue.LastLoggedOnDisplayName
}
Repeat the process if you want to get the last logged on user information from a group of computers.
Note that
in order to get the PowerShell scripts to work on remote computers, there are two prerequisites that need to be met.
- WinRM needs to be enabled on the remote computer
- You need proper credentials to run the script on the remote computer.