Site icon KrookedSkull

PowerShell – Using Query User output as an Object

“Query User” is the perfect tool for administering multi-user systems when you want to see who is currently logged into a system. Open command prompt and type in the command. This command also works even at home when you are the only user of a computer.

Query User

Why is this useful? It’s useful for two reasons: 1) I can see a list of all active users should I need to reboot a system, and 2) I can pull the “ID” to forcibly log off a user by using “logoff <id_number>” from an administrator command prompt.

This post, however, is about how to pull those results and convert them into a powershell object for processing, analysis, and eventual execution.

Here is the full script (note: some of this was pulled from another blog but I was unable to find the source again. I’ll update this post if I can find it):

Function Get-QUser{
     #untested, change (quser) to (quser /server:$computername) if you wanted to extend this into an array of computers
     #you would need to build out the foreach-object loop of computer and specific parameters in the function
    foreach($ServerLine in @(quser) -split "\n") {
        $report = "" | Select-Object UserName, Session, ID, State, IdleTime, LogonTime
        $Parsed_Server = $ServerLine -split '\s+'
        if($Parsed_Server -like "USERNAME*") {continue}
        $report.Username = $Parsed_Server[1]
        $report.Session = $Parsed_Server[2]
        $report.ID = $Parsed_Server[3]
        $report.State = $Parsed_Server[4]
        $report.IdleTime = $Parsed_Server[5]
        $report.LogonTime = $Parsed_Server[6]+" " +$Parsed_Server[7]+" " +$Parsed_Server[8]
        if($Parsed_Server[3] -eq "Disc") {
            $report.Session = "None"
            $report.ID = $Parsed_Server[2]
            $report.State = $Parsed_Server[3]
            $report.IdleTime = $Parsed_Server[4]
            $report.LogonTime = $Parsed_Server[5]+" " +$Parsed_Server[6]+" " +$Parsed_Server[7]
        if($Parsed_Server -like ">*") {
            $report.Username = $Parsed_Server[0]
            $report.Session = $Parsed_Server[1]
            $report.ID = $Parsed_Server[2]
            $report.State = $Parsed_Server[3]
            $report.IdleTime = $Parsed_Server[4]
            $report.LogonTime = $Parsed_Server[5]+" " +$Parsed_Server[6]+" " +$Parsed_Server[7]
    return $quserList

Get-QUser | Format-Table

What’s next?

I needed the above command for a very short need but there was more I wanted to do with this:

Additional Links and References

Exit mobile version