PowerShell fetch the user logged into a workstation
We can query the logged in user via both command prompt and Powershell.
Command Prompt –
C:\Users\61>quser /server:c008
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
61 rdp-tcp#0 2 Active 2:28 8/04/2024 4:58 PM
C:\Users\61>query user /server:C008
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
61 rdp-tcp#0 2 Active 2:28 8/04/2024 4:58 PM
C:\Users\61>
Powershell –
With powershell we can use multiple commands
Option – 1
PS C:\Windows\System32> query user /server:C009
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
61 rdp-tcp#38 2 Active . 20/03/2024 7:37 AM
PS C:\Windows\System32> quser /server:036
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
60 console 1 Active none 12/04/2024 12:31 PM
Option – 2
[cm009]: PS C:\Users\61\Documents> get-wmiobject -class win32_computersystem | select-object -ExpandProperty UserName
[c009]: PS C:\Users\61\Documents> quser
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
61 rdp-tcp#38 2 Active 6 20/03/2024 7:37 AM
or you can use query user.
Another option is to query the event viewer Security logs on that machine.
$filterHashTable = @{
LogName = 'Security'
ID = 4798
}
$events = Get-WinEvent -FilterHashtable $filterHashTable -ErrorAction SilentlyContinue
$events | Select-Object -First 20 | Select-Object timecreated,id,message | Format-Table -AutoSize -Wrap
This will generate the output as follows –
TimeCreated Id Message
----------- -- -------
12/04/2024 5:46:31 PM 4798 A user's local group membership was enumerated.
Subject:
Security ID: S-1-5-18
Account Name: C009$
Account Domain: SONARCHECK
Logon ID: 0x3E7
User:
Security ID: S-1-5-21----504
Account Name: WDAGUtilityAccount
Account Domain: C009
Process Information:
Process ID: 0x16b4
Process Name: C:\Windows\System32\wbem\WmiPrvSE.exe
12/04/2024 5:46:31 PM 4798 A user's local group membership was enumerated.
Subject:
Security ID: S-1-5-18
Account Name: C009$
Account Domain: SONARCHECK
Logon ID: 0x3E7
User:
Security ID: S-1-5-21----501
Account Name: Guest
Account Domain: C009
Process Information:
Process ID: 0x16b4
Process Name: C:\Windows\System32\wbem\WmiPrvSE.exe