sikth1911
sikth1911

Reputation: 21

Using Qwinsta to export a shortened list of disconnected sessions

I need to create an application in Powershell which will list the "Disconnected" remote sessions, it must output the username and the ID of the session which will later be used with rwinsta to remove the session

I found a script on stackoverflow which almost does the proof of concept by searching for the sessions and providing a shortened list which shows only the Username and Session ID but I am struggling to resolve formatting issues. The Foreach and replace is trimming whitespaces and causing the rows to switch columns.

function Get-TSSessions
{
    param ($ComputerName = "SERVER")
    qwinsta /server:$ComputerName | ForEach-Object {$_.Trim() -replace "\s+","," } | ConvertFrom-Csv
}

Get-TSSessions -ComputerName "SERVER2016" | ft -Property USERNAME, ID -AutoSize

I then get the following out:

USERNAME      ID
--------      --
0             Disc
1             Conn
Administrator 5
6             Disc
65536         Listen

If I remove the ForEach-Object {$_.Trim() -replace "\s+","," } from the Qwinsta command and then remove the Format-Table -Property USERNAME, ID -Autosize from the Get-TSSessions - I get the following table:

 SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
 services                                    0  Disc
 console                                     1  Conn
 31c5ce94259d4...  Administrator             5  Active
                   admin2                    6  Disc
 31c5ce94259d4...                        65536  Listen
 rdp-tcp                                 65537  Listen

As you can see, the results in the first table are being moved to the empty space to the left when that column does not contain an entry so the two disconnected sessions do not show the correct Username and ID.

I basically just need the Username and ID columns from the second table to be shown.

Upvotes: 1

Views: 2530

Answers (1)

boxdog
boxdog

Reputation: 8432

EDIT: Updated based on clearer description of the problem

It seems qwinsta.exe outputs its text in fixed-width columns, so the following should correctly replace the spaces to give valid CSV output:

function Get-TSSessions
{
    param ($ComputerName = "SERVER")

    qwinsta /server:$ComputerName |
        ForEach-Object {$_ -replace "\s{2,18}","," } | 
            ConvertFrom-Csv
}

Get-TSSessions -ComputerName "SERVER2016" |
    Where-Object State -eq 'Disc' |
        Format-Table UserName, ID -AutoSize

Upvotes: 1

Related Questions