Improve company productivity with a Business Account.Sign Up

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 7057
  • Last Modified:

VBScript find remote username

Hi all.

I have a VBScript that lists all online computers in our domain and then finds their IP Address, MAC Address and Serial Number, which gets organized into an Excel File

I would like to be able to find out the main user of the desktop/laptop. There will be multiple user profiles on most PC's, so I would consider the largest profile (in MB) to be the default one. If I had a variable called 'HostName', could you write a vbs function to tell me the default user of that machine?

Thanks in advance.
1 Solution
Hello Ryan_R,

Yes, you could use WMI To get the last logged in user...but that may not really be the owner it will just be the last person who used it.  You could use WMI to loop through the documents and settings folder and check size of the folders...and take the largest one and pass it back....


Ryan_RIT Systems AdministratorAuthor Commented:
That's great - can you provide an example - I'm no expert at vb scripting unfortunately (or at WMI)
I'd be a little hesitant to assume the largest profile as that PC's main user.  Many users seem to think their desktop is an ideal storage spot for all their files and if they log onto other PC's then this can ruin the accuracy of your data.

To get the current user using the winmgts here is a function.  What you could do is create a VB script that runs on a users startup.  Include in it their username, PC name etc.  Each time this runs it could deposit this data as line in a database or spreadsheet.  Allow this to run for a couple of weeks and then group your data by username.  You should then be able to effectively locate that user A uses PC x most of the time etc

Public Function NTUser() As String  
Dim objWMISvc As Object, colItems As Object
Dim objItem As Object

    Set objWMISvc = GetObject("winmgmts:\\.\root\cimv2")
    Set colItems = objWMISvc.ExecQuery("Select * from Win32_ComputerSystem", , 48)
    For Each objItem In colItems
        Debug.Print "User Name: " & objItem.UserName
        NTUser = objItem.UserName

End Function

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Ryan_RIT Systems AdministratorAuthor Commented:
I'll try that out after the weekend.

Perhaps there is a way to see how many times each user has logged in to a specific PC during the past 2 weeks?

Hope you guys like challenges, because this is already over my head  :o)
Ryan_RIT Systems AdministratorAuthor Commented:

Do any of you know of some script code that I could try out?
Hi Ryan
Which angle are you wanting to try out?  The script to record details at login, or something to check user profiles, for example, taking the most recent 'last accessed' date.  I can give you a hand with either.

Ryan_RIT Systems AdministratorAuthor Commented:
I think the best method would be to check the size of \\computer\c$\Documents and Settings\username and assume that the largest folder is primary user. However, it would probably also be a good idea to check the last user acces date as well - and have two collumns - one for each check. If the last user who accessed a PC is one of the IT staff, then they can be dismissed as not being the main users.

Ok.  How are you going to run the script?  Via a login script or from a PC?
Ryan_RIT Systems AdministratorAuthor Commented:
From my laptop - I will run a script that creates an Excel file and fills it with 4 collumns - Computer Name, IP Address, MAC Address, and Serial Number. I am hoping to modify the script and add 2 functions that will populate 2 more collumns - on for the last user who logged on and one for who has the largest profile on each machine.
OK, here is some code which will get the last modified date/time for each profile in documents and settings.  Obviously you'll just need the bits to compliment what you already have.

As for the largest profile, that will require a bit more work, as you can't get this from WMI.  Do you have access to all the PCs via an admin share?  i.e. \\computer01\c$
Option Explicit
' This is the CSV file that will contain the conputer name, user profiles and last modified date.
Const OutputFile = "c:\ComputersUsers.csv"
Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20
Const ForWriting = 2
Const ForAppending = 8
Dim fso : set fso = CreateObject("Scripting.FileSystemObject")
Dim flhOutput, strOutput
Dim arrComputers, computer
Dim objWMIService, colSubFolders, folder
' Place code here to compile an array of computer names on your network
arrComputers = Array("computer_name")
For Each computer In arrComputers
	Set flhOutput = fso.opentextfile(OutputFile,ForWriting,true)
	If IsAlive(computer) Then
		Set objWMIService = GetObject("winmgmts:\\" & computer & "\root\CIMV2")
		Set colSubfolders = objWMIService.ExecQuery ("Associators of {Win32_Directory.Name='c:\Documents and Settings'} " _
		 & "Where AssocClass = Win32_Subdirectory ResultRole = PartComponent")
		For Each folder In colSubfolders
			strOutput = computer & "," & folder.Name & "," & WMIDateStringToDate(folder.LastModified)
			flhOutput.Writeline strOutput
	End If
Function IsAlive(target)
	Dim PingResults    
	Dim PingResult     
	Dim return_value
	Dim strComputer
	strComputer = "."
	Set PingResults = GetObject(_
		"winmgmts://" & strComputer & "/root/cimv2"). ExecQuery("SELECT StatusCode, ProtocolAddress FROM Win32_PingStatus " & _
			"WHERE Address = '" & target & "'")
	For Each PingResult In PingResults
		If PingResult.StatusCode = 0 Then
			If LCase(Target) = PingResult.ProtocolAddress Then
				return_value = True
				return_value = True
			End If
			return_value = False
		End If
		IsAlive = return_value
End Function
Function WMIDateStringToDate(dtmDate)
	WMIDateStringToDate = CDate(Mid(dtmDate, 5, 2) & "/" & _
	Mid(dtmDate, 7, 2) & "/" & Left(dtmDate, 4) _
	& " " & Mid (dtmDate, 9, 2) & ":" & Mid(dtmDate, 11, 2) & ":" & Mid(dtmDate,13, 2))
End Function

Open in new window

Ryan_RIT Systems AdministratorAuthor Commented:
Thanks - I'm just on my wa out (Friday night) so you'll have to wait until I get back to work for all the feedback.
Ryan_RIT Systems AdministratorAuthor Commented:
Just reading the code from home (can't really test it now) - but is that script only just telling me when the date when the 'Docs & Settings' folder was last modified instead of the Name of the subfolder in Docs and Settings that was last modified?

Also do you have a function that returns the name of the largest subfolder in Docs and Settings?

If you want me to post my current script - let me know.
The script writes the computer name, profile folder name, and date last modified.  
If you can post what you have I'll combine the two over the weekend.  
Haven't done the folder size yet, see my last post re questions regarding that.

Ryan_RIT Systems AdministratorAuthor Commented:
Hi again - here's the current vbscript
Option Explicit
Dim Row, XL, WshShell, FileSystem, RegularExpression, Dummy, TheNVFile, TheLine
Dim Whacks, WhacksFound, WhacksPattern,  Flag, HostName, NBTable, PingReport, PingPattern
Dim IPAddress, MACPattern, MACAddress, Matches, TheMatch, Match, NBCommand, TheNBTFile
Dim IPCommand, TheIPFile, FileName, TheDate, Suggestion, Book, SerialNo
Const ForReading = 1
Row = 2
Set XL = WScript.CreateObject("Excel.Application")
Set WshShell = WScript.CreateObject("WScript.Shell")
Set FileSystem = CreateObject("Scripting.FileSystemObject")
Set RegularExpression = New RegExp
Dummy = WshShell.Popup ("Compiling Network Address Inventory.  Please Wait...",1,"PC Inventory Utility",64)
Call BuildSpreadSheet()
WshShell.Run "Cmd.exe /c Net View > C:\Windows\Temp\NetViewList.txt", 2,True
Set TheNVFile = FileSystem.OpenTextFile("C:\Windows\Temp\NetViewList.txt", ForReading, True)
Do While TheNVFile.AtEndOfStream <> True
	TheLine = TheNVFile.ReadLine
	Whacks = "\\"
	WhacksFound = FindPattern(TheLine, Whacks)
	If WhacksFound Then
		XL.Cells(Row, 1).Value = "Gathering Information..."
		WhacksPattern = "\\\\\S*"
		Flag = "1"
		HostName = GetPattern(TheLine, WhacksPattern, Flag )
		NBTable = GetNBTable(HostName)
		MACPattern = "MAC Address = \S*"
		Flag = "2"
		MACAddress = GetPattern(NBTable, MACPattern, Flag )
		PingReport = GetIPAddress(HostName)
		PingPattern = "Reply from \S*"
		Flag = "3"
		IPAddress = GetPattern(PingReport, PingPattern, Flag )
		IPAddress = Replace(IPAddress, ":", "") 
		SerialNo = GetSerial(HostName)
		Call AddToSpreadSheet(HostName, IPAddress, MACAddress, SerialNo)
	End If
Row = Row + 1
XL.Cells(Row, 1).Value = "Created " & WeekdayName(Weekday(Date), False, vbSunday) & " " & Day(Date) & " " & MonthName(Month(Date)) & " " & Year(Date)
XL.Cells(Row, 1).Font.Italic = True
'Dummy = WshShell.Popup ("Network Address Inventory Operation Complete",5,"PC Inventory Utility",64 )
Call SaveSpreadSheet()
Sub BuildSpreadSheet()
	XL.Visible = True
	Set Book = XL.WorkBooks.Add
	XL.Columns(1).ColumnWidth = 20
	XL.Columns(2).ColumnWidth = 20
	XL.Columns(3).ColumnWidth = 20
	XL.Columns(4).ColumnWidth = 30
	XL.Cells(1, 1).Value = "Host Name"
	XL.Cells(1, 2).Value = "IP Address"
	XL.Cells(1, 3).Value = "MAC Address"
	XL.Cells(1, 4).Value = "Serial No."
	XL.Selection.Font.Bold = True
	XL.Selection.Font.Size = 12
End Sub
Sub AddToSpreadSheet(HostName, IPAddress, MACAddress, SerialNo)
	XL.Cells(Row, 1).Value = HostName
	If IPAddress <> HostName Then XL.Cells(Row, 2).Value = IPAddress
	If MACAddress <> HostName Then XL.Cells(Row, 3).Value = MACAddress
	XL.Cells(Row, 4).Value = SerialNo
	Row = Row + 1
	XL.Cells(Row, 1).Select
End Sub
Sub SaveSpreadSheet()
	TheDate = Date
	TheDate = Replace(TheDate, "/", "-")
	Suggestion = "PC Inventory " & TheDate & ".xls"
	FileName = XL.GetSaveAsFilename(Suggestion)
	If FileName <> False Then
	End If
End Sub  
Function FindPattern(TheText, ThePattern)
	RegularExpression.Pattern = ThePattern
	If RegularExpression.Test(TheText) Then
		FindPattern = "True"
		FindPattern = "False"
	End If
End Function
Function GetPattern(TheText, ThePattern, Flag)
	RegularExpression.Pattern = ThePattern
	Set Matches = RegularExpression.Execute(TheText) 
	For Each Match in Matches
		TheMatch = Match.Value 
		If Flag = "1" Then TheMatch = Mid(TheMatch, 3)
		If Flag = "2" Then TheMatch = Mid(TheMatch, 14)
		If Flag = "3" Then TheMatch = Mid(TheMatch, 11)
	GetPattern = TheMatch
End Function
Function GetNBTable(HostName)
	NBCommand = "nbtstat -a " & HostName
	WshShell.Run "Cmd.exe /c " & NBCommand &" > C:\Windows\Temp\NBTList.txt", 2,True
	Set TheNBTFile = FileSystem.OpenTextFile("C:\Windows\Temp\NBTList.txt", ForReading, True)
	GetNBTable = TheNBTFile.ReadAll
End Function
Function GetIPAddress(HostName)
	IPCommand = "ping -n 1 " & HostName
	WshShell.Run "Cmd.exe /c " & IPCommand &" > C:\Windows\Temp\IPList.txt", 2,True
	Set TheIPFile = FileSystem.OpenTextFile("C:\Windows\Temp\IPList.txt", ForReading, True)
	GetIPAddress = TheIPFile.ReadAll
End Function
Function GetSerial(strComputer)
	Dim objWMIService, colItems, objItem ',strComputer
    On Error Resume Next
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    If Err.Number = 0 Then
		On Error GoTo 0
		Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_BIOS",,48)
        For Each objItem In colItems
            If Trim(objItem.SerialNumber) <> "" Then
				GetSerial = UCase(objItem.SerialNumber)
            End If
		'Dim strError
		'strError = "ERROR: " & Err.Number & " - " & Err.Description
		'If Err.Number = 462 Then strError = ""
		GetSerial = ""
        On Error GoTo 0
    End If   
End Function

Open in new window

Ryan_RIT Systems AdministratorAuthor Commented:
As you can see, all I really need are 2 functions to add to the end of it that return the username for 1) the last user to logon a computer, and 2) the user with the largest profile on a copmuter. Then I just have to change the top of the script to make 2 more collumns and place the returned data in there.
Ryan_RIT Systems AdministratorAuthor Commented:
Any ideas???
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.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now