Skip to content

Instantly share code, notes, and snippets.

@scriptingstudio
Last active August 1, 2023 10:54
Show Gist options
  • Save scriptingstudio/972ee5f4d6cf56dfcad486b6d7235233 to your computer and use it in GitHub Desktop.
Save scriptingstudio/972ee5f4d6cf56dfcad486b6d7235233 to your computer and use it in GitHub Desktop.
quser.exe PowerShell wrapper
function PSQUser {
param (
[alias('inputobject','server','srv','ipaddress')]
[string[]]$computerName = 'localhost'
)
$quserPattern = @(
'(?<UserName>>?\S+)'
'(?<SessionName>(\w+)?)'
'(?<Id>\d+)'
'(?<State>\w+)'
'(?<IdleTime>[\w\d:.\-]+)'
'(?<LogonTime>[0-9 \-.:]+)'
) -join '\s+'
foreach ($cn in $computerName) {
quser.exe /server:$cn | ForEach-Object {
if ($_ -notmatch $quserPattern) {return}
$session = [PSCustomObject]$matches
$idle = if (-not $session.IdleTime -or $session.IdleTime -match '[\w.-]') {'0:00'}
elseif (-not $session.IdleTime.contains(':')) {"0:$($session.IdleTime)"}
else {"$($session.IdleTime):00"}
$idle = if ($idle -match '(\d+)\+(\d+):(\d+)')
{new-timespan -Days $matches[1] -Hours $matches[2] -Minutes $matches[3]}
else {[timespan]$idle}
[PSCustomObject]@{
ComputerName = if ($cn -eq 'localhost') {$env:ComputerName} else {$cn}
UserName = $session.UserName.trim() -replace '>'
Current = $session.UserName -match '>'
SessionName = $session.SessionName
SessionId = $session.Id
State = $session.State
IdleTime = $idle
LogonTime = [datetime]::parse(($session.LogonTime))
}
}
}
} # END PSQUser
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment