Last active
March 28, 2019 15:16
-
-
Save skunkie/3a4e0ee873fe557e4fca659e8573d230 to your computer and use it in GitHub Desktop.
Get Logged On Users with 'query.exe USER' in PowerShell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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