Powershell: Get-RemoteUsers | Zak Emerick's IT Blog

My IT blog for random ideas and solutions.

Powershell: Get-RemoteUsers


Below is a Powershell function that I wrote to solve an issue of resolving remote/local users before a software application was deployed. So many times do I need to know if an user is logged in before I make any changes. There are few easy ways to retrieve the ‘remote’ users on a remote system. There is the qwinsta.exe command that will retrieve them, but only one at a time, and the formatting doesn’t really work for me pragmatically. I do utilize that command in this script, but I format it in a way that PS can use it (borrowed from poshcode). I then output a nice PSObject that can be manipulated as I need.
This function also allows me to spit 1,000 machines at it and I can retrieve the active users on each one– local and remote sessions. You can see the output below the function.

function Get-RemoteUsers {
Retrieves the active users on a given system(s)
This function will retrive the console and remote desktop users on a given system(s). It utilizes the qwinsta command.
.PARAMETER ComputerName
1 or more computer names that you want to retrieve the active users on. Defaults to local system.
Retrieves the active user sessions on the current system.
Get-RemoteUsers -ComputerName TestComputer
Will retrieve remote and local sessions on the system TestComputer
Outputs a PSObject with SessionType, ComputerName, User as properties.
[string]$ComputerName = $env:COMPUTERNAME
    begin { 
    [array]$outArray = @() 
    process {
        foreach ($Computer in $ComputerName) {
            $query = (qwinsta /server:$Computer | foreach { (($_.trim() -replace "\s+",",")) } | ConvertFrom-Csv)
            foreach ($result in $query) { 
                $user = $result.USERNAME
                $sessionType = $result.SESSIONNAME  
                If (($user -match "[a-z]") -and ($user -ne $null)) {  
                    $splatProp = @{
                $outObj = New-Object -TypeName PSObject -Property $splatProp 
                $outArray += $outObj
    end { Write-Output $outArray }


SessionType                                     ComputerName                                   User                                          
-----------                                     ------------                                   ----                                          
console                                         SERVER01                                       tinyjesus                                     
rdp-tcp#0                                       SERVER01                                       babyjewus
console                                         SERVER02                                       tinyjesus
321 Total Views 1 Views Today

Post a Comment

Your email address will not be published. Required fields are marked *

 characters available