Windows – Who is currently logged on to a device
Here is the thing, the main reason I went looking for how to do this was because of risk. The risk that when you go to do some work on someone’s PC you end up working on the wrong one. Multiple reasons this could happen, you have been given the wrong hostname, the remote access tool information is out of date, to name two.
This short Powershell script wanders off to a nominated device and lets you know who is logged on to it:
#Get the name of the account currently logged on to a Windows device
$UserPc = Read-Host -Prompt 'Please enter a computer name'
$LOUser = (Get-WmiObject -computername $UserPC -class Win32_ComputerSystem).username
if ($LOUser -eq $null) {
Write-Output "No user is currently logged on to $UserPC."
}
else
{
$LOUser = $LOUser.split("\")[1]
Write-Output $LOUser
}
Let’s go ahead and break it down into the separate parts for some explanation what the code does.
$UserPc = Read-Host -Prompt 'Please enter a computer name'
When the script is run, the first thing it does is ask for the device name to be queried. Can’t do much without it now can we!
$LOUser = (Get-WmiObject -computername $UserPC -class Win32_ComputerSystem).username
Now the script takes information that has been entered and queries the devices for an active user on the device.
if ($LOUser -eq $null) {
Write-Output "No user is currently logged on to $UserPC."
}
The first half of the conditional statement that executes next checks if the query returned a value. If it did not, $LOUser would be null or be empty, so we need to capture it or we will end up with an error.
else
{
$LOUser = $LOUser.split("\")[1]
Write-Output $LOUser
}
If there is a value to $LOUser then the second half of the conditional statement will execute returning the user id. You will note that the code splits the returned value. This is because the response will include the domain and user id separated by \.
It is useful to separate out the user id so that this can then be reused for subsequent queries sent to Active Directory for example.