Kill Remote Desktop Session from Target in vb.net

I was asked to write code that upon request will kill remote desktop connections from the target machine upon request. Here is what I came up with. If it helps please do let me know.
 
Dim lstrFileName As String = IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "temp.txt")
 
        Process.Start("QUERY USER /SERVER:localhost > " & lstrFileName)
        '
        '**************Sample out put of above command written to lstrFileName*********************
        '
        'USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME
        'achappar              rdp-tcp#11          1  Active          .  25.04.2008 23:55
        '
 
        Dim lobjStreamReader As New IO.StreamReader(lstrFileName)
 
        '
        'Skip the header line 
        '
        lobjStreamReader.ReadLine()
 
        While Not lobjStreamReader.EndOfStream
            '
            'Terminate all the sessions. 
            '
 
            Dim lstrSessionId As String = lobjStreamReader.ReadLine.Trim.Replace("  ", " ")
 
            'Replace multiple spaces with single space
            Dim lstrTemp As String = lstrSessionId.Trim.Replace("  ", " ")
 
            While lstrTemp.Length <> lstrSessionId.Length
                lstrSessionId = lstrTemp
                lstrTemp = lstrSessionId.Trim.Replace("  ", " ")
            End While
 
            'get the session id at the third field ( index 2)
            'if needed you can terminate a particular user session by comparing his name availabe at index 1 below
            lstrSessionId = lstrTemp.Split(" "c)(2)
            '
            'Now close the session
            'This will close the user session. You can also use LOGOFF SESSION instead if you want to logoff the user
            Process.Start("RESET SESSION " & lstrSessionId & " /SERVER:localhost")
 
        End While
 
        lobjStreamReader.Close()

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: