[Last Call] Learn how to a build a cloud-first strategyRegister Now


Terminal services Q

Posted on 2007-08-01
Medium Priority
Last Modified: 2010-03-05

This is related to this Q.

Question by:bsharath
  • 5
  • 5
LVL 12

Accepted Solution

zoofan earned 2000 total points
ID: 19609845
Here is the updated terminal server sessions log script. Output has changed to a csv file of

ComputerName   Available sessions  Active Sessions    Inactive Sessions    Total Sessions    Max Sessions

This order can be changed easily so if you want to let me know.

'===Start copy: getsessions.vbs===
' ---------------------------------------------------------------'
' getsessions.vbs
' 'Sample VBScript to query remote computers
' 'and return terminal service's sessions into csv file.
' ''Author Riley C. aka ZooFan
' '''Version 4.1 - 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
Dim strMaxCons 'Split max connection settings
'---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."
            Elseif strPCFile = "" Then
                  MsgBox "You must enter a filename!",vbOKOnly,"Get live sessions from remote computers."
            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 & ".csv"
                                                If objFSO.FileExists(strResultsFile) Then
                                                      Set objOutputFile = objFso.CreateTextFile(strResultsFile)
                                                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
                              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."
                                          '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."
                                                      End If
                                                '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."
                                          End If
                                    End If
                              Call runquery                        
                        End If      
            End If
'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
Dim GetMaxConnections
Dim avlConnections
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")
                              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 = objItem.TotalSessions
                                       strActive = objItem.ActiveSessions
                                       strInActive = objItem.InactiveSessions
                              If strSessions = "" Or strActive = "" Or strInActive = "" Then
                              getsessions = "Error"
                              GetMaxConnections = 0
                              Set colItems = wbemServices.ExecQuery ("Select * from Win32_TSNetworkAdapterSetting")
                              For Each objItem in colItems
                                  GetMaxConnections = GetMaxConnections + objItem.MaximumConnections
                              avlConnections = GetMaxConnections - strSessions
                              getsessions = strComputer & "," & avlConnections  & "," & strActive & "," & strInActive& "," & strSessions & "," & GetMaxConnections
                        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
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
                                    '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))
                                                                  arrValSplit = split(getsessions(arrPCnames(intPCLoop)),",")
                                                             End If
                                    MsgBox "File has been processed, and results saved in " & strResultsFile ,vbOKOnly,"Get live sessions from remote computers."
End sub                        
'===End copy: getsessions.vbs===

Any problems let me know

LVL 11

Author Comment

ID: 19609903

Any help on the other Questions.
LVL 12

Expert Comment

ID: 19609927
Working on the other installed apps.

Is not really a safe way to look for other installed apps by name as you need the exact name to look for if you want accuracy,  however I can and have exported a complete list of all posted apps installed under add remove programs if that will do.

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 12

Expert Comment

ID: 19609942
I currently have that outputting to a txt file named by pcname(from a read in file)  and lists all installed apps from add remove programs.

LVL 11

Author Comment

ID: 19609946
Yes that would be great in the same formal in excel .
Like headers and if it can scan the machines in the file.Then thats what i want.
LVL 12

Expert Comment

ID: 19609991
Well doing this in excel isnt benifical as it is just a line by line list of app names.

I could do a single excel line for each pc with each app in a cell, but I think that would be very hard to read

Either a file for each pc


or excel containing all pc's

cell        cell         cell          cell      cell
pc1        app1      app2      app3   app4
pc2        app1       app2     app3   app4

and yes it reads your pcname file to query from.

LVL 11

Author Comment

ID: 19610035
A excel with machine name and all softwares in each cell.
LVL 12

Expert Comment

ID: 19610168
ok post a question, getting all installed apps from add remove programs of remote computers into excel

LVL 11

Author Comment

ID: 19610206
LVL 11

Author Comment

ID: 19614240
One small attachment in the same script if possible.To find which Os the machine is running with

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Welcome to my series of short tips on migrations. Whilst based on Microsoft migrations the same principles can be applied to any type of migration. My first tip is around source server preparation. No migration is an easy migration, there is a…
Background Information Recently I have fixed file server permission issues for one of my client. The client has 1800 users and one Windows Server 2008 R2 domain joined file server with 12 TB of data, 250+ shared folders and the folder structure i…
Windows 8 comes with a dramatically different user interface known as Metro. Notably missing from the new interface is a Start button and Start Menu. Many users do not like it, much preferring the interface of earlier versions — Windows 7, Windows X…
Windows 8 came with a dramatically different user interface known as Metro. Notably missing from that interface was a Start button and Start Menu. Microsoft responded to negative user feedback of the Metro interface, bringing back the Start button a…
Suggested Courses

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question