Powershell Script to Get Logged In Users of One Particular Machine in the Domain

Hi All,

While learning Powershell I am trying to make a script that will prompt me for my Domain Admin account details and then the Hostname that I would like to check to see who is currently logged in and whether the machine is locked/active/logged out/turned off.

I have the below so far, but unable to see why I keep getting errors when testing on my own machine that I do have admin access to,

Any ideas please?

Error I am getting is: "Error browsing Network...."


#Get my domain Admin Account details
$Creds = Get-Credential

#To Query a PC for Current Logged in State
$ComputerName = Read-host "Please enter the Hostname"

#query user /server:$ComputerName -credential $Creds
C:\scripts\psloggedon.exe -accepteula \\$ComputerName -credential $Creds



  • #Get Admin Account details $Creds = Get-Credential #To Query a PC for Current Logged in State $ComputerName = Read-host "Please enter the Hostname" #query user /server:$ComputerName -credential $Creds C:\scripts\psloggedon.exe -accepteula \\$ComputerName -credential $Creds

  • Why not just use...

    query user /server:LabServerOrWorkstationName

    ... no creds required

    You state you are already domain admin in the org, which means you are already
    a admin on every system in the org.

    You can just run a PoSH session elevated as a domain admin and you don't have
    to enter creds to run commands.

    function Get-LoggedOnUser

    param ($TargetHostname)

    if(-not$TargetHostname) { read-host -Prompt "Enter Remote Computer Name" }

    $ExplorerProcess = Get-WmiObject -class win32_process -computername $TargetHostname `
    | where name -Match explorer

    if($ExplorerProcess -eq $null) {
    $LoggedOnUser = "No current user"
    #elseif($ExplorerProcess.getowner().user.count -gt 1){
    # $LoggedOnUser = $ExplorerProcess.getowner().user[0]
    $LoggedOnUser = $ExplorerProcess.getowner().user
    return $LoggedOnUser

    Get-LoggedOnUser -TargetHostname LabServerOrWorkstationName

    # Or use
    $AdminCreds = Get-Credential -Credential "$env:USERDOMAIN\$env:USERNAME"
    Invoke-Command -ComputerName LabServerOrWorkstationName -ScriptBlock {'whatever command you want to run'} -Credential $AdminCreds
  • In reply to postanote:

    Im not near a pc now so cant test but think i did try something similar though it didnt show time stamps or if they were active or locked screen etc.

    I do hqve doman admire n access though its under a different account.
    Eg my everyday account is peter
    My admin account is peterx3

  • In reply to Private_IT_Support:

    Is there one method thats better/more reliable than others. I basically need to query a machine on a different floor qnd see if the user is logged into and a time stamp. Also if technically possibly i was hoping to see if its currently locked or in-use?

    Which way do u think i should leave ok into, the query user or pstools etc?

  • In reply to Private_IT_Support:

    No worries...

    The thing to remember here, is when creds are required to get info and when they are not. There are may cmdlets which do not require creds to get info from remote hosts.

    I never log into my workstation with domain admin creds or even local admin creds. I always use my non-priv account.

    Now, that being said, my hosts have PoSH Execution policy set to Restricted or Remote Signed. Yet, I have two sets of PoSH shortcuts on my taskbar.

    One set is the default normal user ones, and a configured set for admin work, which are set to run as domain admin and always run elevated.

    My two domain admin PoSH shortcuts are configured as shown. This means only the current session is running at these level, not the host. It also allows me to test my code / scripts as two different users non-priv and priv'd.

    Console Host:
    C:\Windows\System32\runas.exe /user:contoso\Administrator "%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted"

    C:\Windows\System32\runas.exe /user:contoso\Administrator "%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy UnRestricted PowerShell_ISE.exe"

    Both are set to always run as admin by using the shortcut Advanced button and checking the box as well as set to always Start In my scripts folder.

    I do this same kind of thing for Windows MMC's as well. Well, I actually create on Master MMC and put all the available Windows management consoles there and pin that to the taskbar for use.

    C:\Windows\System32\runas.exe /user:contoso\Administrator "mmc C:\Tools\MasterTaskpad.msc"

    Thus, one console to rule them all...Anyway, enough noise about my work style...

    As for your goal...

    The fastest route to get what you are after is what we've already covered. 'Query', since it give you both things you need where PsLoggedOn does not, thus you need to do something else to get the locked or not stuff.

    $TargetHostname = 'SomeRemoteHostName'

    query user /server:$TargetHostname

    HostUser rdp-tcp#3 3 Active 2:42 11/5/2017 4:47 PM

    It does not require any creds for the target to get this information and only has two status types.

    • Active: Logged in and using
    • Disconnected: logged in but the screen is locked or user is detached

    - Or do this with WMI class or CIM Class instance, which my require creds if you are not already running in an remote admin elevated session.

    $RemoteAdminCreds = Get-Credential -Credential "$env:USERDOMAIN\$env:USERNAME"

    Invoke-Command -ComputerName $TargetHostname `
    -ScriptBlock {
    'The current logged on user is: ' + $env:USERNAME
    (Get-WMIObject -class Win32_Desktop `
    | Select Name,ScreenSaverActive) -match $env:USERNAME
    (Get-Process) -match 'LogonUI'
    } -Credential $RemoteAdminCreds

    The current logged on user is: RemoteUser

    Name : contoso\remoteuser
    ScreenSaverActive : False
    PSComputerName : SomeRemoteHostName
    RunspaceId : 5d1847cd-bb39-4ef2-98dc-6dfd2ea22eb8

    Id : 880
    Handles : 323
    CPU : 0.125
    Name : LogonUI
    PSComputerName : SomeRemoteHostName

    If the ScreenSaver returns 'true' then the host is locked
    LogonUI is a process that is running when a user is interactive.
    Of course the LogonUI is the MS Gina, that Windows logon box we all see.
  • In reply to postanote:

    Clever thinking, I never thought of modifying the Shortcut to launch ISE as an Admin
  • In reply to postanote:


    I've opted for the easier option for now to save time as it captures pretty much all I need, for now while i'm learning


    $TargetHostname = 'localhost'

    query user /server:$TargetHostname


    However, I'm puzzled with the results:

    How can Idle Time be 1 Day and 7 hours, when i just turned it on about 1.5 hours ago this evening?

  • In reply to Private_IT_Support:

    Easier is almost always best. I say almost, because sometimes easier does not get you all you want.
    As for what you are seeing in the time slot, that is not uptime.

    The idle time (the number of minutes since the last keystroke or mouse movement at the session)
    More details here:

    If you are after uptime, you'd try something like....

    # Getting host up time, by converting the computer’s last boot time into a DateTime then subtract that from the current Get-Date
    (Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime((Get-WmiObject Win32_OperatingSystem).LastBootUpTime))