Make-QUSERobject.ps1

# Script Name: Make-QUSERobject.ps1
# Current Version: 1.0
# Written By: Peter Remstad
# Date Created: 2020-01-03
# Date Revised: 2020-01-03
#
# Notes: v1.0 - Converts the QUSER command from string output to a PS object. This allows
# for easier scripting against user sessions.
#
############################################################################################

<#PSScriptInfo
 
.VERSION 1.0
 
.GUID a880a1c8-4fd4-484f-b6d5-28c012756fac
 
.AUTHOR Peter Remstad
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS QUSER User Session
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
.PRIVATEDATA
 
#>


<#
 
.DESCRIPTION
 A concise script that converts QUSER output to a PS object. This allows for easier PS scripting to manage user sessions on remote systems.
 
#>
 

Param()

function Make-QUSERobject
(
    [Parameter(mandatory=$false)]$Server
)
{
    # RESERVES VARIABLES
    $UserSessions = @()
    $LogonTime = $null
    $Session = $null
    $SessionCnt = $null

    # RUNS QUSER AND CAPTURES DATA, REMOVES ALL BULK SPACES AND REPLACES WITH A SINGLE SPACE
    If ($Server -eq $null) {
        $QResults = quser
        $Server = $env:COMPUTERNAME
    } Else {
        $QResults = quser /SERVER:$Server
    }
    $QResults = $QResults -replace '\s+', ' '

    # CREATES OBJECT FOR EACH RETURNED RESULT
    Foreach ($Line in $QResults[1..$QResults.GetUpperBound(0)]) {
        #Separates the data
        $Split = $Line.Split(' ').Split('>')

        # SESSIONNAME IS BLANK WHEN THE SESSION IS DISCONNECTED. MODIFIES DATA ACCORDINGLY.
        If ($Split[3] -eq 'Disc') {
            $Session = ""
            $SessionCnt = 1
        }  Else {
            $Session = $Split[2]
            $SessionCnt = 2
        }

        # CREATES OBJECTS
        $UserSessions += [pscustomobject]@{
            USERNAME = $Split[1]
            SESSIONNAME = $Session
            ID = $Split[$SessionCnt + 1]
            STATE = $Split[$SessionCnt + 2]
            IDLE_TIME = $Split[$SessionCnt + 3]
            LOGON_TIME = ($Split[($SessionCnt + 4)..($SessionCnt + 6)] -join ' ')
            SERVER = $Server
        }

        # RESETS LOOP VARIABLES
        $Session = $null
        $SessionCnt = $null
    }

    Return $UserSessions
}

Make-QUSERobject