Find all the machine i am connected.

Hi,

I want to find how many Mstsc session are live on my machine.How can i find this.

regards
Sharath
LVL 11
bsharathAsked:
Who is Participating?
 
zoofanCommented:
Here is the modified results output to resturcture the file as asked.

'===Start copy: getsessions.vbs===
' ---------------------------------------------------------------'
' getsessions.vbs
' 'Sample VBScript to query remote computers
' 'and return terminal service's sessions.
' ''Author Riley C. aka ZooFan
' '''Version 3.3 - July 2007
' ''''www.experts-exchange.com question ID: 22722261
' ---------------------------------------------------------------'
'
Option Explicit
'Declare variables
Const ForReading = 1, ForWriting = 2, ForAppending = 3 'FileObject Access Type
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0 'FileObject Format Type
Dim objWbemLocator'Object for WScript used in (Function getsessions) to connect to remote pc
Dim objFso 'Object for WScript used to access our file system
Dim objWshShell'Object for WScript used in (Function IsDomainAdmin) to get logon server name
Dim objNetwork 'Object for WScript used in (Function IsDomainAdmin) to retreive list of groups and members
Dim objOutputFile 'Object for WScript used for our results
Dim objPCnames 'Object for WScript used to open the pc list file
Dim objReadFile 'Object for WScript used to read the pc list file
Dim strPCFile 'Store path and name of file used for pc list
Dim strUsername 'Store username
Dim strPassword 'Store Password
Dim strCurPath 'Store our current path
Dim strResultsFile 'Our results file
Dim intLneCount 'Our loop counter for each line of pc list
Dim dte 'Used to store date so we can format it to valid file name charset
Dim tme 'Used to store time so we can format it to valid file name charset
Dim intPCLoop ' Used for pc array name loop counter
Dim strReturn 'The return string from function getsessions
Dim arrValSplit 'The array for results returned from function getsessions
'---Setup required objects
      Set objWbemLocator = CreateObject("WbemScripting.SWbemLocator")
      Set objFso = CreateObject("Scripting.FileSystemObject")
      Set objWshShell = WScript.CreateObject("WScript.Shell")
      Set objNetwork = CreateObject("WScript.Network")
      strCurPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")
'---Get file with computer list      
      strPCFile = InputBox("Please enter the full path and file" & VbCrLf & "name of the file with the computer names.","Get live sessions from remote computers.")
            'Test to make sure file exists if not exit script
            If Not objFso.FileExists(strPCFile) Then
                  MsgBox "You must enter a valid full path and file name!",vbOKOnly,"Get live sessions from remote computers."
                WScript.Quit(0)
            Elseif strPCFile = "" Then
                  MsgBox "You must enter a filename!",vbOKOnly,"Get live sessions from remote computers."
                WScript.Quit(0)               
            Else 'File exists continue
                                    'Create New text file for outputting our results
                                    dte = Replace(FormatDateTime(date(),vbshortdate),"/","-")
                                    tme = Replace(Replace(FormatDateTime(now(),vbLongtime),":","-")," ","")
                                          strResultsFile = strCurPath & "\" & tme & "_" & dte & ".txt"
                                                If objFSO.FileExists(strResultsFile) Then
                                                      ObjFSO.deleteFile(strResultsFile)
                                                Else
                                                      Set objOutputFile = objFso.CreateTextFile(strResultsFile)
                                                      objOutputFile.Close      
                                                End If
'-----------Get user account
                  strUsername = objNetwork.userName
                        'If current logged on user is not a memeber of administrators get a username
                        If IsDomainAdmin(strUsername) = True Then
'-----------------------Loop through file list
                                    strUsername = "current"
                                    strPassword = "current"
                                    Call runquery
                                    WScript.Quit(0)
                        Else
                              strUsername = InputBox("Please enter a username with adminsitrative access.","Get live sessions from remote computers.")
                                    If strUsername = "" Then
                                          MsgBox "You must enter a username!",vbOKOnly,"Get live sessions from remote computers."
                                    Else
                                          'If username entered is a member of adminsitrators get the password
                                          If IsDomainAdmin(strUsername) = True Then
                                                strPassword = InputBox("Please enter the password for that user account.","Get live sessions from remote computers.")
                                                      If strPassword = "" Then
                                                            MsgBox "You must enter a password!",vbOKOnly,"Get live sessions from remote computers."
                                                            WScript.Quit(0)
                                                      End If
                                          Else
                                                'User entered is not a member of adminsitrators group exit script
                                                MsgBox "That user account does not have adminsitrative rights!",vbOKOnly,"Get live sessions from remote computers."
                                                WScript.Quit(0)
                                          End If
                                    End If
                              Call runquery                        
                        End If      
            End If
      WScript.Quit(0)
'Function to return number of sessions of passed computer name      
Function getsessions(strComputer)
Dim strSessions 'Store total sessions
Dim strActive 'Store active sessions
Dim strInActive      'Store inactive sessions
Dim wbemServices
Dim Testme
Dim iErr
Dim colItems
Dim objItem
On Error Resume Next
      Set Testme = GetObject("winmgmts:\\" & strComputer,"Root\CIMV2")
      iErr = Hex(Err.Number)
            Select Case Ucase(iErr)
                Case 0
                        If strUsername = "current" And strPassword = "current" Then
                              Set wbemServices = objWbemLocator.ConnectServer(strComputer,"Root\CIMV2")
                        Else
                              Set wbemServices = objWbemLocator.ConnectServer(strComputer,"Root\CIMV2",strUsername,strPassword)
                        End If
                        Set colItems = wbemServices.ExecQuery("Select * from Win32_PerfFormattedData_TermService_TerminalServices",,48)
                              For Each objItem in colItems
                                       strSessions = " Total Sessions : " &  objItem.TotalSessions
                                       strActive = " Active Sessions : " & objItem.ActiveSessions
                                       strInActive = " Idle Sessions : " & objItem.InactiveSessions
                              Next
                              If strSessions = "" Or strActive = "" Or strInActive = "" Then
                              getsessions = "Error"
                              else
                              getsessions = strSessions & "," & strActive & "," & strInActive
                              End If
            Case Else
                        getsessions = "Error"
            End Select
End Function
'Function to test passed user account for Administrator group membership.
Function IsDomainAdmin(strUser)
Dim strDomainDC
Dim objGroup
Dim objMember
strDomainDC = objWshShell.ExpandEnvironmentStrings("%LOGONSERVER%")
strDomainDC = Mid(strDomainDC,3,(len(strDomainDC)-2))
Set objGroup = GetObject("WinNT://" & strDomainDC & "/Administrators" & ",group")
For Each objMember In objGroup.Members
  if lcase(objMember.Name) = lcase(strUser) Then
        IsDomainAdmin = True
  end If
Next
End Function
Sub runquery
                                    'Read the list of computers into arrPCnames
                                    Set objPCnames = objFso.GetFile(strPCFile)
                                    Set objReadFile = objPCnames.OpenAsTextStream(ForReading, TristateUseDefault)
                                          Do Until objReadFile.AtEndOfStream
                                                ReDim Preserve arrPCnames(intLneCount)
                                                arrPCnames(intLneCount) = objReadFile.ReadLine
                                                intLneCount = intLneCount + 1
                                          Loop
                                    objReadFile.Close
                                    'Run a query on each pc in the list and output the reults to our file
                                          Set objOutputFile = objFso.OpenTextFile(strResultsFile,ForWriting,TristateUseDefault)
                                                For intPCLoop = LBound(arrPCnames) To UBound(arrPCnames)
                                                      strReturn = getsessions(arrPCnames(intPCLoop))
                                                            If strReturn = "Error" Then
                                                                   objOutputFile.WriteLine("Error connecting to: " & arrPCnames(intPCLoop))
                                                             Else
                                                                  arrValsplit = split(getsessions(arrPCnames(intPCLoop)),",")
                                                                  objOutputFile.WriteLine("Machine name : " & arrPCnames(intPCLoop) & arrValSplit(1) & arrValSplit(2) & arrValSplit(0) & vbcrlf)
                                                             End If
                                                Next
                                           objOutputFile.Close      
                                    MsgBox "File has been processed, and results saved in " & strResultsFile ,vbOKOnly,"Get live sessions from remote computers."
End sub                        
'===End copy: getsessions.vbs===



zf
0
 
RazwerCommented:
you mean how many connections are currently connected to the server you are logged on to?
on the server you go to administrative tools-->terminal services manager.
you can see "this computer" how many are connected to that server, and if they are active. Take over sessions if you are connected to the terminal yourself, or check other servers what their state is with terminal connections...
0
 
gurutcCommented:
Hi,

You can open a command prompt, and type NETSTAT -A and press Enter to see all the network connections currently running on your system.  The ones on port 3389 are the terminal server ones.

- gurutc
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
Alan Huseyin KayahanCommented:
         Hi Sharath
                 *Start>Run>cmd
                 * qwinsta
                    qwinsta will show you all sessions including the console session

Regards
0
 
bsharathAuthor Commented:
Sorry i got you confused.I want to know how many machines i have connected to.
Say i have connected to 10 Mstsc sessions in 10 machines.I want to know there names i am connected now.
From my machine to which machines i have connected.
0
 
RazwerCommented:
that case only gurutc's solution will work for you. No other way on a client pc to find that out...
0
 
bsharathAuthor Commented:
Netstat-A.

I get this.

  Proto  Local Address          Foreign Address        State
  TCP    dev-chen-mrd100:epmap  dev-chen-mrd100.Development..co.uk:0
LISTENING
  TCP    dev-chen-mrd100:microsoft-ds  dev-chen-mrd100.Development..co
.uk:0  LISTENING
  TCP    dev-chen-mrd100:1025   dev-chen-mrd100.Development..co.uk:0
LISTENING
  TCP    dev-chen-mrd100:1055   dev-chen-mrd100.Development..co.uk:0
LISTENING
  TCP    dev-chen-mrd100:1056   dev-chen-mrd100.Development..co.uk:0
LISTENING
  TCP    dev-chen-mrd100:1534   dev-chen-mrd100.Development..co.uk:0
LISTENING
  TCP    dev-chen-mrd100:2002   dev-chen-mrd100.Development..co.uk:0
LISTENING
  TCP    dev-chen-mrd100:2425   dev-chen-mrd100.Development..co.uk:0
LISTENING
  TCP    dev-chen-mrd100:3389   dev-chen-mrd100.Development..co.uk:0
LISTENING
  TCP    dev-chen-mrd100:8192   dev-chen-mrd100.Development..co.uk:0
LISTENING
  TCP    dev-chen-mrd100:8193   dev-chen-mrd100.Development..co.uk:0
LISTENING
  TCP    dev-chen-mrd100:8194   dev-chen-mrd100.Development..co.uk:0
LISTENING
  TCP    dev-chen-mrd100:1045   dev-chen-mrd100.Development..co.uk:104
6  ESTABLISHED
  TCP    dev-chen-mrd100:1046   dev-chen-mrd100.Development..co.uk:104
5  ESTABLISHED
  TCP    dev-chen-mrd100:1048   dev-chen-mrd100.Development..co.uk:104
9  ESTABLISHED
  TCP    dev-chen-mrd100:1049   dev-chen-mrd100.Development..co.uk:104
8  ESTABLISHED
  TCP    dev-chen-mrd100:1110   dev-chen-mrd100.Development..co.uk:200
2  ESTABLISHED
  TCP    dev-chen-mrd100:2002   dev-chen-mrd100.Development..co.uk:111
0  ESTABLISHED
  TCP    dev-chen-mrd100:netbios-ssn  dev-chen-mrd100.Development..co.
uk:0  LISTENING
  TCP    dev-chen-mrd100:microsoft-ds  dev-chen-pc1014.development..co
.uk:3938  ESTABLISHED
  TCP    dev-chen-mrd100:microsoft-ds  dev-chen-pc2021.development..co
.uk:2101  ESTABLISHED
  TCP    dev-chen-mrd100:1053   in-isa-srv1.development..co.uk:8080  E
STABLISHED
  TCP    dev-chen-mrd100:1054   dev-chen-mrd100.Development..co.uk:819
4  ESTABLISHED
  TCP    dev-chen-mrd100:1056   dev-chen-mrd100.Development..co.uk:105
7  ESTABLISHED
  TCP    dev-chen-mrd100:1057   dev-chen-mrd100.Development..co.uk:105
6  ESTABLISHED

But i am connected to 4 machine through Mstsc.They are not displayed here .What does the other Ports mean
0
 
gurutcCommented:
Hi,

Try this:  Go to this link and get What is Transferring

http://www.majorgeeks.com/What_Is_Transferring_d4703.html

This will show the traffic from your system to other IPs

- gurutc
0
 
zoofanCommented:
Terminal Services Client?
How about
"HOW TO: Use WinStation Monitor to Monitor Terminal Services Client Sessions"
http://support.microsoft.com/kb/320190



zf
0
 
zoofanCommented:
Or a script to monitor sessions

From: http://forums.adventnet.com/viewtopic.php?=&p=80645

' Check command line parameters

On Error Goto 0
Set objWbemLocator = CreateObject("WbemScripting.SWbemLocator")
'On Error Resume Next
Select Case WScript.Arguments.Count
   Case 1
      strComputer = Wscript.Arguments(0)
      Set wbemServices = objWbemLocator.ConnectServer(strComputer,"Root\CIMV2")
     
   Case 3
      strComputer = Wscript.Arguments(0)
      strUsername = Wscript.Arguments(1)
      strPassword = Wscript.Arguments(2)
      Set wbemServices = objWbemLocator.ConnectServer(strComputer,"Root\CIMV2",strUsername,strPassword)

   Case Else
      strMsg = "Error # in parameters passed"
      WScript.Echo strMsg
      WScript.Quit(0)
   
End Select

if Err.Number Then
   WScript.Echo vbCrLf & "Error # " & _
                " " & Err.Description
End If
On Error GoTo 0

'On Error Resume Next      
Set colItems = wbemServices.ExecQuery("Select * from Win32_PerfFormattedData_TermService_TerminalServices",,48)
if Err.Number Then
   WScript.Echo vbCrLf & "Error # " & _
             " " & Err.Description
End If
On Error GoTo 0
   
For Each objItem in colItems
   WScript.Echo "TotalSessions" & vbTab & objItem.TotalSessions
   WScript.Echo "ActiveSessions" & vbTab & objItem.ActiveSessions
   WScript.Echo "InactiveSessions" & vbTab & objItem.InactiveSessions
Next

WScript.Quit(0)



zf
0
 
bsharathAuthor Commented:
I get this error.

---------------------------
Windows Script Host
---------------------------
Error # in parameters passed
---------------------------
OK  
---------------------------
0
 
zoofanCommented:
You need to pass the paramters on the command line for it.

See the case's

Case 1 If you only want to enter the computer name
case 3 if you want to enter the computer name/username/password


IE:
filename.vbs computername
filename.vbs computername,username,password  <-----IN THIS ORDER


zf
0
 
zoofanCommented:
Just retested on a 03 server and works fine here.

zf
0
 
zoofanCommented:
As noted in your other question,  the paramters need to passed after the filename and they are space delemitted.

filename.vbs computername username password  <-----IN THIS ORDER


My appologize as my previous post using comma's was probably confusing.


zf
0
 
zoofanCommented:
Have you gotten thie script working ok?

zf
0
 
bsharathAuthor Commented:
zoofan
Sorry for the delay.
Can this script scan all machine names in a file and get me the results to a file.
0
 
zoofanCommented:
Yes you need to pass the Computer name as a paramter, and if required the creditials of a user with rights spaces in between see below.

Local machine or Remote machine already logged in as a admin
filename.vbs computername

remote machine using a user account or a machine which is not part of the domain
filename.vbs computername username password  <-----IN THIS ORDER spaces between the parameters


zf
0
 
zoofanCommented:
DO not add the \\ to the pc name,  use just pcname

filename.vbs pcname


zf
0
 
bsharathAuthor Commented:
If i want to do this for 30 machines then?
0
 
zoofanCommented:
lol
I would have made some changes to it.
But
  "how many Mstsc session are live on my machine"

zf
0
 
zoofanCommented:
Am editing it for you now.

zf
0
 
bsharathAuthor Commented:
Thanks
0
 
zoofanCommented:
Will have to finish up tonight time for work.

Going to take a bit as dealing with a fail in the list it would be nice if it just went on to the next one instead of closing!

zf
0
 
gurutcCommented:
hey, zoofan's solution is very nice.

- gurutc
0
 
zoofanCommented:
Hi bsharath,

Here is the completed script with the changes.  When you run it will ask you (Inputbox) for the path to the file containing the list of pc's.  If you are not logged in with an account that is the member of the "administrators" group on the DC will ask you for a user name and password of a user that is in the "administrators" group(again via input boxes).  When the script is finished it will let you with a message box, and output the results into a text file in the directory where the script is run from with the name generated from the time and date the script was executed. hh-mm-ssAM_dd-mm-yyyy.txt

The pc file should look like this

Pc1Name
Pc2Name
Pc3Name

'===Start copy: getsessions.vbs===
' ---------------------------------------------------------------'
' getsessions.vbs
' 'Sample VBScript to query remote computers
' 'and return terminal service's sessions.
' ''Author Riley C. aka ZooFan
' '''Version 2.9 - July 2007
' ''''www.experts-exchange.com question ID: 22722261
' ---------------------------------------------------------------'
'
Option Explicit
'Declare variables
Const ForReading = 1, ForWriting = 2, ForAppending = 3 'FileObject Access Type
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0 'FileObject Format Type
Dim objWbemLocator'Object for WScript used in (Function getsessions) to connect to remote pc
Dim objFso 'Object for WScript used to access our file system
Dim objWshShell'Object for WScript used in (Function IsDomainAdmin) to get logon server name
Dim objNetwork 'Object for WScript used in (Function IsDomainAdmin) to retreive list of groups and members
Dim objOutputFile 'Object for WScript used for our results
Dim objPCnames 'Object for WScript used to open the pc list file
Dim objReadFile 'Object for WScript used to read the pc list file
Dim strPCFile 'Store path and name of file used for pc list
Dim strUsername 'Store username
Dim strPassword 'Store Password
Dim strCurPath 'Store our current path
Dim strResultsFile 'Our results file
Dim intLneCount 'Our loop counter for each line of pc list
Dim dte 'Used to store date so we can format it to valid file name charset
Dim tme 'Used to store time so we can format it to valid file name charset
Dim intPCLoop ' Used for pc array name loop counter
Dim strReturn 'The return string from function getsessions
Dim arrValSplit 'The array for results returned from function getsessions
'---Setup required objects
      Set objWbemLocator = CreateObject("WbemScripting.SWbemLocator")
      Set objFso = CreateObject("Scripting.FileSystemObject")
      Set objWshShell = WScript.CreateObject("WScript.Shell")
      Set objNetwork = CreateObject("WScript.Network")
      strCurPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")
'---Get file with computer list      
      strPCFile = InputBox("Please enter the full path and file" & VbCrLf & "name of the file with the computer names.","Get live sessions from remote computers.")
            'Test to make sure file exists if not exit script
            If Not objFso.FileExists(strPCFile) Then
                  MsgBox "You must enter a valid full path and file name!",vbOKOnly,"Get live sessions from remote computers."
                WScript.Quit(0)
            Elseif strPCFile = "" Then
                  MsgBox "You must enter a filename!",vbOKOnly,"Get live sessions from remote computers."
                WScript.Quit(0)               
            Else 'File exists continue
'-----------Get user account
                  strUsername = objNetwork.userName
                        'If current logged on user is not a memeber of administrators get a username
                        If IsDomainAdmin(strUsername) = True Then
'-----------------------Loop through file list
                                    strUsername = "current"
                                    strPassword = "current"
                                    'Create New text file for outputting our results
                                    dte = Replace(FormatDateTime(date(),vbshortdate),"/","-")
                                    tme = Replace(Replace(FormatDateTime(now(),vbLongtime),":","-")," ","")
                                          strResultsFile = strCurPath & "\" & tme & "_" & dte & ".txt"
                                                If objFSO.FileExists(strResultsFile) Then
                                                      ObjFSO.deleteFile(strResultsFile)
                                                Else
                                                      Set objOutputFile = objFso.CreateTextFile(strResultsFile)
                                                      objOutputFile.Close      
                                                End If
                                    'Read the list of computers into arrPCnames
                                    Set objPCnames = objFso.GetFile(strPCFile)
                                    Set objReadFile = objPCnames.OpenAsTextStream(ForReading, TristateUseDefault)
                                          Do Until objReadFile.AtEndOfStream
                                                ReDim Preserve arrPCnames(intLneCount)
                                                arrPCnames(intLneCount) = objReadFile.ReadLine
                                                intLneCount = intLneCount + 1
                                          Loop
                                    objReadFile.Close
                                    'Run a query on each pc in the list and output the reults to our file
                                          Set objOutputFile = objFso.OpenTextFile(strResultsFile,ForWriting,TristateUseDefault)
                                                For intPCLoop = LBound(arrPCnames) To UBound(arrPCnames)
                                                      strReturn = getsessions(arrPCnames(intPCLoop))
                                                            If strReturn = "Error" Then
                                                                   objOutputFile.WriteLine("Error connecting to: " & arrPCnames(intPCLoop))
                                                             Else
                                                                  arrValsplit = split(getsessions(arrPCnames(intPCLoop)),",")
                                                                  objOutputFile.WriteLine(arrPCnames(intPCLoop) & " reported " & arrValSplit(0) & arrValSplit(1) & arrValSplit(2) & vbcrlf)
                                                             End If
                                                Next
                                           objOutputFile.Close      
                                    MsgBox "File has been processed, and results saved in " & strResultsFile ,vbOKOnly,"Get live sessions from remote computers."
                                    WScript.Quit(0)

                        Else
                              strUsername = InputBox("Please enter a username with adminsitrative access.","Get live sessions from remote computers.")
                                    If strUsername = "" Then
                                          MsgBox "You must enter a username!",vbOKOnly,"Get live sessions from remote computers."
                                    Else
                                          'If username entered is a member of adminsitrators get the password
                                          If IsDomainAdmin(strUsername) = True Then
                                                strPassword = InputBox("Please enter the password for that user account.","Get live sessions from remote computers.")
                                                      If strPassword = "" Then
                                                            MsgBox "You must enter a password!",vbOKOnly,"Get live sessions from remote computers."
                                                            WScript.Quit(0)
                                                      End If
                                          Else
                                                'User entered is not a member of adminsitrators group exit script
                                                MsgBox "That user account does not have adminsitrative rights!",vbOKOnly,"Get live sessions from remote computers."
                                                WScript.Quit(0)
                                          End If
                                    End If                        
                        End If      
            End If
      WScript.Quit(0)
'Function to return number of sessions of passed computer name      
Function getsessions(strComputer)
Dim strSessions 'Store total sessions
Dim strActive 'Store active sessions
Dim strInActive      'Store inactive sessions
Dim wbemServices
Dim Testme
Dim iErr
Dim colItems
Dim objItem
On Error Resume Next
      Set Testme = GetObject("winmgmts:\\" & strComputer,"Root\CIMV2")
      iErr = Hex(Err.Number)
            Select Case Ucase(iErr)
                Case 0
                        If strUsername = "current" And strPassword = "current" Then
                              Set wbemServices = objWbemLocator.ConnectServer(strComputer,"Root\CIMV2")
                        Else
                              Set wbemServices = objWbemLocator.ConnectServer(strComputer,"Root\CIMV2",strUsername,strPassword)
                        End If
                        Set colItems = wbemServices.ExecQuery("Select * from Win32_PerfFormattedData_TermService_TerminalServices",,48)
                              For Each objItem in colItems
                                       strSessions = " TotalSessions: " & vbTab & objItem.TotalSessions
                                       strActive = " ActiveSessions: " & vbTab & objItem.ActiveSessions
                                       strInActive = " InactiveSessions: " & vbTab & objItem.InactiveSessions
                              Next
                              If strSessions = "" Or strActive = "" Or strInActive = "" Then
                              getsessions = "Error"
                              else
                              getsessions = strSessions & "," & strActive & "," & strInActive
                              End If
            Case Else
                        getsessions = "Error"
            End Select
End Function
'Function to test passed user account for Administrator group membership.
Function IsDomainAdmin(strUser)
Dim strDomainDC
Dim objGroup
Dim objMember
strDomainDC = objWshShell.ExpandEnvironmentStrings("%LOGONSERVER%")
strDomainDC = Mid(strDomainDC,3,(len(strDomainDC)-2))
Set objGroup = GetObject("WinNT://" & strDomainDC & "/Administrators" & ",group")
For Each objMember In objGroup.Members
  if lcase(objMember.Name) = lcase(strUser) Then
        IsDomainAdmin = true
  end If
Next
End Function
'===End copy: getsessions.vbs===


If you have any troubles let me know.


zf

0
 
bsharathAuthor Commented:
Zoofan
I get this in the txt file

Error connecting to: indiasophos
dev-chen-mrd100 reported  TotalSessions:       1 ActiveSessions:       1 InactiveSessions:       0

Error connecting to: dev-chen-nas01
dev-chen-pc5000 reported  TotalSessions:       1 ActiveSessions:       1 InactiveSessions:       0

dev-chen-pc5001 reported  TotalSessions:       1 ActiveSessions:       1 InactiveSessions:       0

Why is it showing 1 inactivesession
0
 
zoofanCommented:
One second,  sorry I pasted the wrong file.


'===Start copy: getsessions.vbs===
' ---------------------------------------------------------------'
' getsessions.vbs
' 'Sample VBScript to query remote computers
' 'and return terminal service's sessions.
' ''Author Riley C. aka ZooFan
' '''Version 3.2 - July 2007
' ''''www.experts-exchange.com question ID: 22722261
' ---------------------------------------------------------------'
'
Option Explicit
'Declare variables
Const ForReading = 1, ForWriting = 2, ForAppending = 3 'FileObject Access Type
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0 'FileObject Format Type
Dim objWbemLocator'Object for WScript used in (Function getsessions) to connect to remote pc
Dim objFso 'Object for WScript used to access our file system
Dim objWshShell'Object for WScript used in (Function IsDomainAdmin) to get logon server name
Dim objNetwork 'Object for WScript used in (Function IsDomainAdmin) to retreive list of groups and members
Dim objOutputFile 'Object for WScript used for our results
Dim objPCnames 'Object for WScript used to open the pc list file
Dim objReadFile 'Object for WScript used to read the pc list file
Dim strPCFile 'Store path and name of file used for pc list
Dim strUsername 'Store username
Dim strPassword 'Store Password
Dim strCurPath 'Store our current path
Dim strResultsFile 'Our results file
Dim intLneCount 'Our loop counter for each line of pc list
Dim dte 'Used to store date so we can format it to valid file name charset
Dim tme 'Used to store time so we can format it to valid file name charset
Dim intPCLoop ' Used for pc array name loop counter
Dim strReturn 'The return string from function getsessions
Dim arrValSplit 'The array for results returned from function getsessions
'---Setup required objects
      Set objWbemLocator = CreateObject("WbemScripting.SWbemLocator")
      Set objFso = CreateObject("Scripting.FileSystemObject")
      Set objWshShell = WScript.CreateObject("WScript.Shell")
      Set objNetwork = CreateObject("WScript.Network")
      strCurPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")
'---Get file with computer list      
      strPCFile = InputBox("Please enter the full path and file" & VbCrLf & "name of the file with the computer names.","Get live sessions from remote computers.")
            'Test to make sure file exists if not exit script
            If Not objFso.FileExists(strPCFile) Then
                  MsgBox "You must enter a valid full path and file name!",vbOKOnly,"Get live sessions from remote computers."
                WScript.Quit(0)
            Elseif strPCFile = "" Then
                  MsgBox "You must enter a filename!",vbOKOnly,"Get live sessions from remote computers."
                WScript.Quit(0)               
            Else 'File exists continue
                                    'Create New text file for outputting our results
                                    dte = Replace(FormatDateTime(date(),vbshortdate),"/","-")
                                    tme = Replace(Replace(FormatDateTime(now(),vbLongtime),":","-")," ","")
                                          strResultsFile = strCurPath & "\" & tme & "_" & dte & ".txt"
                                                If objFSO.FileExists(strResultsFile) Then
                                                      ObjFSO.deleteFile(strResultsFile)
                                                Else
                                                      Set objOutputFile = objFso.CreateTextFile(strResultsFile)
                                                      objOutputFile.Close      
                                                End If
'-----------Get user account
                  strUsername = objNetwork.userName
                        'If current logged on user is not a memeber of administrators get a username
                        If IsDomainAdmin(strUsername) = True Then
'-----------------------Loop through file list
                                    strUsername = "current"
                                    strPassword = "current"
                                    Call runquery
                                    WScript.Quit(0)
                        Else
                              strUsername = InputBox("Please enter a username with adminsitrative access.","Get live sessions from remote computers.")
                                    If strUsername = "" Then
                                          MsgBox "You must enter a username!",vbOKOnly,"Get live sessions from remote computers."
                                    Else
                                          'If username entered is a member of adminsitrators get the password
                                          If IsDomainAdmin(strUsername) = True Then
                                                strPassword = InputBox("Please enter the password for that user account.","Get live sessions from remote computers.")
                                                      If strPassword = "" Then
                                                            MsgBox "You must enter a password!",vbOKOnly,"Get live sessions from remote computers."
                                                            WScript.Quit(0)
                                                      End If
                                          Else
                                                'User entered is not a member of adminsitrators group exit script
                                                MsgBox "That user account does not have adminsitrative rights!",vbOKOnly,"Get live sessions from remote computers."
                                                WScript.Quit(0)
                                          End If
                                    End If
                              Call runquery                        
                        End If      
            End If
      WScript.Quit(0)
'Function to return number of sessions of passed computer name      
Function getsessions(strComputer)
Dim strSessions 'Store total sessions
Dim strActive 'Store active sessions
Dim strInActive      'Store inactive sessions
Dim wbemServices
Dim Testme
Dim iErr
Dim colItems
Dim objItem
On Error Resume Next
      Set Testme = GetObject("winmgmts:\\" & strComputer,"Root\CIMV2")
      iErr = Hex(Err.Number)
            Select Case Ucase(iErr)
                Case 0
                        If strUsername = "current" And strPassword = "current" Then
                              Set wbemServices = objWbemLocator.ConnectServer(strComputer,"Root\CIMV2")
                        Else
                              Set wbemServices = objWbemLocator.ConnectServer(strComputer,"Root\CIMV2",strUsername,strPassword)
                        End If
                        Set colItems = wbemServices.ExecQuery("Select * from Win32_PerfFormattedData_TermService_TerminalServices",,48)
                              For Each objItem in colItems
                                       strSessions = " TotalSessions: " & vbTab & objItem.TotalSessions
                                       strActive = " ActiveSessions: " & vbTab & objItem.ActiveSessions
                                       strInActive = " InactiveSessions: " & vbTab & objItem.InactiveSessions
                              Next
                              If strSessions = "" Or strActive = "" Or strInActive = "" Then
                              getsessions = "Error"
                              else
                              getsessions = strSessions & "," & strActive & "," & strInActive
                              End If
            Case Else
                        getsessions = "Error"
            End Select
End Function
'Function to test passed user account for Administrator group membership.
Function IsDomainAdmin(strUser)
Dim strDomainDC
Dim objGroup
Dim objMember
strDomainDC = objWshShell.ExpandEnvironmentStrings("%LOGONSERVER%")
strDomainDC = Mid(strDomainDC,3,(len(strDomainDC)-2))
Set objGroup = GetObject("WinNT://" & strDomainDC & "/Administrators" & ",group")
For Each objMember In objGroup.Members
  if lcase(objMember.Name) = lcase(strUser) Then
        IsDomainAdmin = true
  end If
Next
End Function
Sub runquery
                                    'Read the list of computers into arrPCnames
                                    Set objPCnames = objFso.GetFile(strPCFile)
                                    Set objReadFile = objPCnames.OpenAsTextStream(ForReading, TristateUseDefault)
                                          Do Until objReadFile.AtEndOfStream
                                                ReDim Preserve arrPCnames(intLneCount)
                                                arrPCnames(intLneCount) = objReadFile.ReadLine
                                                intLneCount = intLneCount + 1
                                          Loop
                                    objReadFile.Close
                                    'Run a query on each pc in the list and output the reults to our file
                                          Set objOutputFile = objFso.OpenTextFile(strResultsFile,ForWriting,TristateUseDefault)
                                                For intPCLoop = LBound(arrPCnames) To UBound(arrPCnames)
                                                      strReturn = getsessions(arrPCnames(intPCLoop))
                                                            If strReturn = "Error" Then
                                                                   objOutputFile.WriteLine("Error connecting to: " & arrPCnames(intPCLoop))
                                                             Else
                                                                  arrValsplit = split(getsessions(arrPCnames(intPCLoop)),",")
                                                                  objOutputFile.WriteLine(arrPCnames(intPCLoop) & " reported " & arrValSplit(0) & arrValSplit(1) & arrValSplit(2) & vbcrlf)
                                                             End If
                                                Next
                                           objOutputFile.Close      
                                    MsgBox "File has been processed, and results saved in " & strResultsFile ,vbOKOnly,"Get live sessions from remote computers."
End sub                        
'===End copy: getsessions.vbs===


The first one will not work unless you are already logged on with a memeber of the "Administrators" group.  Sorry about that I copied and pasted the wrong file.  You can disregard it, as this is the correct one.


zf
0
 
zoofanCommented:
The inactive sessions are the zeros at the end


zf
0
 
zoofanCommented:
Would you like the results file structured differently? if so give me the layout. keep it simple please!

zf
0
 
bsharathAuthor Commented:
Results like this.

Machine name : Dev-chen-mrd100  Active sessions   : 1 Idle sessions  : 0   Total sessions : 1

If possible how many sessions are available in TS.
 
0
 
bsharathAuthor Commented:
I get this in the file
dev-chen-pc5000 reported  TotalSessions:       1 ActiveSessions:       1 InactiveSessions:       0

dev-chen-pc5001 reported  TotalSessions:       1 ActiveSessions:       1 InactiveSessions:       0
Here the machines are already connected but still shows 0
0
 
bsharathAuthor Commented:
I checked with this machine.

I am on the console and connected a mstsc also.
But i get this
dev-chen-mrd100 reported  TotalSessions:       2 ActiveSessions:       2 InactiveSessions:       0
0
 
zoofanCommented:
umm an account logged in the desktop of that pc? as with 0 mstsc connections I show 1 when logged into the desktop.

zf
0
 
zoofanCommented:
Actually the remote console is using one If Im not mistaken.


zf
0
 
zoofanCommented:
And if you are remoted into that ts server in any way as admin, or logged onto the desktop it uses one (rdp-tcp admin license of the two you get for free)


zf
0
 
zoofanCommented:
Remote into the desktop and log in. Open  Terminal servicesconfiguration manager in admin tools and youll see it there.

zf
0
 
bsharathAuthor Commented:
Great i get this.

Machine name : dev-chen-mrd100 Active Sessions : 1 Idle Sessions : 0 Total Sessions : 1

But how can we find how many terminal access this machine is configured to.

See this Q.
http://www.experts-exchange.com/OS/Microsoft_Operating_Systems/Q_22712673.html
If you can combine this .Then it is of great use.
0
 
zoofanCommented:
I kinda thought it was already of great use myself, but what the hay.

zf
0
 
bsharathAuthor Commented:
zoofan
this is of great use but what i said is if you can solve the other question issue with this.So that we can have 1 script for multiple uses.
What do you think.
At present shall i close this Q.Can you combine this with the other Q and put in the code.
0
 
zoofanCommented:
You can close this one and I will work on the other one with the direction and intent of combining the scripts

zf
0
 
zoofanCommented:
You should also point farhankazi over here as he may already have a solution for combining them.
zf
0
 
bsharathAuthor Commented:
Thanks a lot Zoofan
0
 
zoofanCommented:
my pleasure.

zf
0
 
gurutcCommented:
Very nice, bookmarking this question. - gurutc
0
 
zoofanCommented:
Thanks.

zf
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.