As an Administrator, I have been asked more than once to find out where a computer is on the network. This question is usually asked by someone that needs to inventory or lifecycle the equipment. If your IT department is well organized or you have some sort of 3rd party software running that does this for you, you probably don’t have a whole lot of use for this script.
If, on the other hand, you’re the 1 man/woman IT shop at a small business with no access to 3rd party tools… this script may save you some time. All we want to know is what user is currently logged in to the machine, or the last user to log in. The assumption is, if we know the user, it’s fairly easy to find out where he or she sits within your organization.
Option 1 – This snippet simply reads all the user profiles on the machine, sorts them in descending order by LastWriteTime and selects the first 1… Pretty simple.
Option 2 – This snippet uses the win32_process WMI class to get the username of any user that has an Explorer process open. If you’re logged in, you have an Explorer process running… Also, pretty simple.
If you have some other method using PowerShell, I would love to hear about it. Leave it in the comments of the YouTube video.
# *** THIS SCRIPT IS PROVIDED WITHOUT WARRANTY, USE AT YOUR OWN RISK *** <# .DESCRIPTION Retrieve the username of the user that logged into a computer last. .NOTES File Name: Get-LastLoggedInUser.ps1 Author: David Hall Contact Info: Website: www.signalwarrant.com Twitter: @signalwarrant Facebook: facebook.com/signalwarrant/ Google +: plus.google.com/113307879414407675617 YouTube Subscribe link: https://www.youtube.com/c/SignalWarrant1?sub_confirmation=1 Requires: Tested: PowerShell Version 5, Windows 10 and Windows Server 2k12 R2 .PARAMETER ComputerName .EXAMPLE #> # Option 1 $computer = 'dc1' Get-ChildItem "\\$computer\c$\Users" | Sort-Object LastWriteTime -Descending | Select-Object Name, LastWriteTime -first 1 # Option 2 (Get-WmiObject -Class win32_process -ComputerName $computer | Where-Object name -Match explorer).getowner().user