Skip to content

Instantly share code, notes, and snippets.

@skunkie
Last active March 28, 2019 15:16
Show Gist options
  • Save skunkie/3a4e0ee873fe557e4fca659e8573d230 to your computer and use it in GitHub Desktop.
Save skunkie/3a4e0ee873fe557e4fca659e8573d230 to your computer and use it in GitHub Desktop.
Get Logged On Users with 'query.exe USER' in PowerShell
function Get-LoggedOnUser {
param(
[string[]] $ComputerName=$env:COMPUTERNAME
)
Begin {
$ErrorActionPreference = 'Stop'
& cmd /c ver | Out-Null
$encoding = [Console]::OutputEncoding
[Console]::OutputEncoding = [System.Text.Encoding]::GetEncoding('utf-8')
}
Process {
foreach ($name in $ComputerName) {
try {
$sessions = (& query.exe USER /SERVER:$name) -replace '\s{2,22}', ';' | `
ConvertFrom-Csv -Delimiter ';'
} catch {
[PSCustomObject]@{
'USERNAME' = $null
'SESSIONNAME' = $null
'ID' = $null
'STATE' = $null
'IDLE TIME' = $null
'LOGON TIME' = $null
'COMPUTERNAME' = $name
'ERROR' = $_.Exception
}
continue
}
foreach ($session in $sessions) {
Add-Member -InputObject $session -NotePropertyMembers @{
'COMPUTERNAME' = $name
'ERROR' = $null
}
$session
}
}
}
End {
[Console]::OutputEncoding = $encoding
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment