Skip to content

Instantly share code, notes, and snippets.

@bixb0012
Created September 30, 2025 16:06
Show Gist options
  • Select an option

  • Save bixb0012/be95d594b983581fc305bcccc388e777 to your computer and use it in GitHub Desktop.

Select an option

Save bixb0012/be95d594b983581fc305bcccc388e777 to your computer and use it in GitHub Desktop.
PowerShell: RDS Users
# Reference: 1) https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/query-user
# Example 1: Query user sessions locally on a Remote Desktop Session Host, parse results as a
# formatted table using Substring, and return session information as a properly-typed
# PowerShell object
query user |
Select-Object -Skip 1 |
ForEach-Object {
[pscustomobject]@{
UserName = $_.Substring(1, 20).Trim()
SessionName = $_.Substring(23, 15).Trim()
Id = $_.Substring(40, 4) -as [int]
State = $_.Substring(46, 6).Trim()
IdleTime = $(
try {
[timespan]::ParseExact(
$_.Substring(54, 9).Trim(),
[string[]]("d\+h\:m", "h\:m", "%m"),
$null
)
} catch [FormatException] {
0 -as [timespan]
}
)
LogonTime = $_.Substring(65, $_.Length - 65) -as [datetime]
}
}
# Example 2: Query user sessions locally on a Remote Desktop Session Host, parse results as a
# formatted table using regular expression, and return session information as a
# properly-typed PowerShell object
# Adapted from https://stackoverflow.com/questions/39212183/easier-way-to-parse-query-user-in-powershell-or-quser/62491383#62491383
query user |
Select-Object -Skip 1 |
ForEach-Object {
$Result = $_ -match "^.(.{20}) (.{15}) (.{4}) (.{6}) (.{9}) (.{17,19})$"
if ($Result) {
[pscustomobject] @{
UserName = $Matches[1].Trim()
SessionName = $Matches[2].Trim()
Id = $Matches[3].Trim() -as [int]
State = $Matches[4].Trim()
IdleTime = $(
try {
[timespan]::ParseExact(
$Matches[5].Trim(),
[string[]]("d\+h\:m", "h\:m", "%m"),
$null
)
} catch [FormatException] {
0 -as [timespan]
}
)
LogonTime = $Matches[6].Trim() -as [datetime]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment