Saturday 7 June 2014

Powershell | Get all active RDP sessions for a username

For any IT admin/dev, the ecosystem involves connecting and managing multiple remote desktop sessions to different servers and computers, this can get very cumbersome to maintain and make sure you are disconnecting, many of you probably use mRemote or Remoter Desktop Connection manager to help you manage all of your different connections (if you don't, you really should, its a godsend to be able to categorise and organise all of your connections).

The problem comes in when you have an unexpected crash or an issue and either your computer crashes or the RDP app crashes, you can loose track of which connection you have open, that can lead to leaving sessions open taking up valuable resources or hogging sessions other people need.

That problem can be solved with this powershell script:

<#
.Synopsis
   Gets all server entries from an RDPC connection file and shecks for any open sessons
.EXAMPLE
   get-rdpsessions "C:\resources\rdpSettings.rdg" 'benjamin.dev'
#>
function get-rdpsessions()
{
    Param(
        # link to the RDPC connections file
        $rdcManagerFile,
        # default username to use incase the conneciton entry doesnt have a username set, this should be without the domain
        $defaultUsername)
    
    Select-Xml -XPath '//server' -Path "C:\resources\rdpSettings.rdg" | %{
        $server = $_.node.name
        $userName = $defaultUsername
        if ($_.Node.logonCredentials.HasChildNodes)
        {
            $userName =  $_.Node.logonCredentials.userName
        }
    
        $queryResults = (qwinsta /server:$server | foreach { (($_.trim() -replace “\s+”,”,”))} | ConvertFrom-Csv)
        $queryResults |  %{
            if ($_.SESSIONNAME -eq $userName)
            { 
                write-host 'User:' $_.SESSIONNAME 'is active on' $server -ForegroundColor green
            }
        }
    }
}

get-rdpsessions "C:\resources\rdpSettings.rdg" 'benjamin.dev'

This will output something like the following:

PS C:\Users\benjamin.dev> C:\Users\benjamin.dev\SkyDrive\Code\PS\get-rdpsessions.ps1
User: benjamin.dev is active on devnet-ad.devnet.local
User: benjamin.dev is active on devnet-sql.devnet.local
User: benjamin.dev is active on devnet-sp14.devnet.local
User: benjamin.dev is active on devnet-sp15.devnet.local

This script can be easily modified to integrate with whatever system you use, for example, if you run a development house or consultancy, this could be modified to run through all servers for all users at 4:50 in the afternoon every day and email anyone who has an active session to remind them they need to log off

No comments:

Post a Comment