VBScript to give computer information based on a file search.

Hello Gurus,

I am looking for help with a script i am trying to peice together. I need to scan all of the computers in our network for a file that is in a specific location and report back the computername, ipaddress, user ID, and date the file was modified.

I have peiced together the code you see below, i know it is very dirty code but i am new to VBscripts. I started by using a small OU in our AD structure so i dont have to wait a long time for results. It currently gives me the information i need but i am having trouble getting it to only produce the computers with the file i am looking for.

Any help will be greatly welcomed.

' VBScript Source File -- Created with SAPIEN Technologies PrimalScript 4.1
' NAME: 
' AUTHOR:  , 
' DATE  : 4/9/2009
Dim objOU, objChild, objWMIService, objFSO	
Set objOU = GetObject ("LDAP://ou=Site,ou=State,ou=Region,dc=domain,dc=com")
objOU.Filter = Array("computer")
For Each objChild In objOU
	Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & objChild.DNSHostName & "\root\cimv2")
	Set colFileList = objWMIService.ExecQuery ("ASSOCIATORS OF {Win32_Directory.Name='C:\Program Files\DCI'} Where " & "ResultClass = CIM_DataFile")
				WScript.Echo "   Name:		" & objChild.Name
 				WScript.Echo "   Class:		" & objChild.Class
 				WScript.Echo "   Host Name:		" & objChild.DNSHostName
				Set IPConfigSet = objWMIService.ExecQuery ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled=TRUE")
					For Each IPConfig in IPConfigSet
    					If Not IsNull(IPConfig.IPAddress) Then 
        					For i=LBound(IPConfig.IPAddress) to UBound(IPConfig.IPAddress)
    							WScript.Echo "   IP Address:		" & IPConfig.IPAddress(i)
    					End If
				Set colComputer = objWMIService.ExecQuery ("Select * from Win32_ComputerSystem")
					For Each objComputer In colComputer
						WScript.Echo "   User ID:		" & objComputer.UserName
WScript.Echo "DONE"

Open in new window

Who is Participating?

Improve company productivity with a Business Account.Sign Up

HubasanConnect With a Mentor Commented:
Ok so here is the script you were looking for. It will at present search for ALL computer objects in the domain including servers and workstations, but you can change that. Just look through the script it is well commented. Log file will be created in the folder where the script is executed from.

Good Luck :-)
'= Script Name:			GetFileLastModified.vbs
'= Author:					Denis Hubanic
'= Created on:			2009-04-10
'= Last Modified:		YYYY-MM-DD
'= By:							
'= Version:					1.0
'= Description:			Script scans AD and creates a collection of all computer objects to perform
'= Description:			information gathering on specific file modified date, logged on user 
'= Description: 		and IP Address
'= Notes:						
'Define sublevel search for computer object in the given domain
'Title of the finish window
Const cTitle = "Scan AD For ucmadmt.sf"
'Set the file to look for. Notice double backslashes needed.
sFile = "C:\\Program Files\\DCI\\ucmdmt.sf"
'Define standard objects for FileSystem, Shell and Network. Not all are used
Set oFS = Createobject("Scripting.FileSystemobject")
Set oWS = CreateObject("WScript.Shell")
Set oNet = CreateObject("wscript.network")
'Set script log file to be created in the same folder as the script
sScriptName = WScript.ScriptName
sScriptPath = WScript.ScriptFullName
sLog = Replace(sScriptName, ".vbs", ".csv")
sLogFile = Replace(sScriptPath, sScriptName, sLog)
Set oLogFile = oFS.CreateTextFile(sLogFile,True)
'Connect to the RootDSE of the domain and get the domain path
Set oRootDSE = GetObject("LDAP://rootDSE")
sADsPath = "LDAP://" & oRootDSE.Get("defaultNamingContext")
Set oDomain = GetObject(sADsPath)
'User ADODB to connect to the DSOObject to set up a search for computer objects
Set oConnection = CreateObject("ADODB.Connection")
Set oCommand =   CreateObject("ADODB.Command")
oConnection.Provider = "ADsDSOObject"
oConnection.Open "Active Directory Provider"
Set oCOmmand.ActiveConnection = oConnection
'Below you will find several different computer object search options
'User this search for ALL Computer objects in the Domain
oCommand.CommandText = _
    "Select Name, Location from '" & sADsPath & "' " _
        & "Where objectClass='computer'"
'Use this search for Windows XP computers ONLY (Uncomment lines below this one)
'oCommand.CommandText = _
'    "Select Name, Location from '" & sADsPath & "' " _
'        & "Where objectClass='computer' and " _
'        & "operatingSystemVersion = '5.1 (2600)'"
'Other OS searches can be:
'Windows 2000 Server = 5.0 (2195)
'Windows XP Professional = 5.1 (2600)
'Windows Server 2003 = 5.2 (3790)
'Windows Vista" Business = 6.0 (6000)
'Windows Vista" Ultimate = 6.0 (6001)
'Set search parameters and execute a search to create a collection of computer objects
oCommand.Properties("Page Size") = 5000
oCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 
Set oRecordSet = oCommand.Execute
'Write first log file line with header cells
oLogFile.WriteLine "Computer Name,Status,IP Address,User ID,File Last Modified"
'Loop through all computer objects and performe actions on them
Do Until oRecordSet.EOF
	On Error Resume Next
	'Set variables for computername and status
	sComputer = oRecordSet.Fields("Name").Value
	sComputer = UCase(sComputer)
	sStatus = ""
	'Ping the computer and get the status before continuing
	sIsOnline = Ping(sComputer)
	If IsNull(sIsOnline) Then
		sStatus = "Computer not in the domain"
		oLogFile.WriteLine sComputer & "," & sStatus
	ElseIf sIsOnline = 11013 Then
		sStatus = "TTL Expired Transit"
		oLogFile.WriteLine sComputer & "," & sStatus
	ElseIf sIsOnline = 11010 Then
		sStatus = "Offline"
		oLogFile.WriteLine sComputer & "," & sStatus
	ElseIf sIsOnline = 0 Then
		'If computer is online then proceed to evaluate the status of WMI on the remote PC
		'This should be a common practice since lot's of software outthere can screw up WMI
		sWMIState = CheckWMI(sComputer)
		'if WMI is OK then proceed to check if the file we are looking for exists.
		If sWMIState = "" Then
			sStatus = "Online"
			'Check for the existance of file we are looking for
			sFileLastModified = GetFileLastModified(sComputer,sFile)
			If IsEmpty(sFileLastModified) Then
				sStatus = "File not found"	
				'if the file exists then get IP address and Current user otherwise skip
				sIPAddress = GetIP(sComputer)
				sCurrentUser = GetCurrentUser(sComputer)
				If IsNull(sCurrentUser) Then
					sCurrentUser = "No user Logged in"
				End If
			End If
			'if file is not found then record the status and computer name in the log file
			If sStatus = "File not found" Then
				oLogFile.WriteLine sComputer & "," & sStatus
				'If computer Is online, WMI is OK and file is found, then write all that in the log file.
				oLogFile.WriteLine sComputer & "," & sStatus & "," & sIPAddress & "," & sCurrentUser & "," & sFileLastModified
			End If
		End If
	End If
	'go to the next computer
'Display the message that script is done.
oWS.Popup "Script execution finished!" & vbNewLine &_
"Check your log file: " & sLogFile, ,cTitle ,vbInformation
'============================== Begin Functions ===================================
Function GetIP(sComputer)
	Set oWMI = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & sComputer & "\root\cimv2")
  Set colItems = oWMI.ExecQuery _
	  ("Select * from	Win32_NetworkAdapterConfiguration "_
	  & "where IPEnabled=TRUE",,48)
  For Each oItem in colItems
  	If Not IsNull(oItem.IPAddress) Then			
				sLocalIP = oItem.IPAddress(i)
				Exit For
  	End If
  GetIP = sLocalIP
End Function
'Connect to Remote Computers' WMI and make sure that connection works
Function CheckWMI(sComputer)
	CheckWMI = ""
	On Error Resume Next
	Set oSWbemLocator = CreateObject("WbemScripting.SWbemLocator")		
	Set oWMIService = oSWbemLocator.ConnectServer(sComputer,"root\CIMV2","","","","",&H80)
		If Err.Number <> 0 Then
			CheckWMI = "WMI Issue - can't get file date"
		End If
End Function
Function GetFileLastModified(sComputer,sFile)
	Set oWMIService = GetObject("winmgmts:" _
	    & "{impersonationLevel=impersonate}!\\" & sComputer & "\root\cimv2")
	Set colFiles = oWMIService.ExecQuery _
	    ("Select LastModified from CIM_Datafile Where name = '" & sFile & "'")
	For Each oFile in colFiles
	    sDate = oFile.LastModified
	    sDate = UTCtoStandard(sDate)
	GetFileLastModified = sDate 
End Function
Function UTCtoStandard(CreationDate)
 UTCtoStandard = CDate(Mid(CreationDate, 5, 2) & "/" & _
 Mid(CreationDate, 7, 2) & "/" & Left(CreationDate, 4) _
 & " " & Mid (CreationDate, 9, 2) & ":" & _
 Mid(CreationDate, 11, 2) & ":" & Mid(CreationDate, _
 13, 2))
End Function
Function GetCurrentUser(sComputer)
	Set oWMI = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & sComputer & "\root\cimv2")
	Set colComputer = oWMI.ExecQuery _
    ("Select * from Win32_ComputerSystem")
	For Each oComputer in colComputer
    GetCurrentUser = oComputer.UserName
End Function
Function Ping(sComputer)
Set oWMI = GetObject(_ 
Set colPings = oWMI.ExecQuery _
    ("Select * From Win32_PingStatus where Address = '" & sComputer & "'")
For Each oStatus in colPings
	Ping = oStatus.StatusCode
'    Data type: uint32
'    Access type: Read-only
'    Ping command status codes.
'    Value 	Meaning
'    0    Success
'    Null			Could not find host
'    11001    Buffer Too Small
'    11002    Destination Net Unreachable
'    11003    Destination Host Unreachable
'    11004    Destination Protocol Unreachable
'    11005    Destination Port Unreachable
'    11006    No Resources
'    11007    Bad Option
'    11008    Hardware Error
'    11009    Packet Too Big
'    11010    Request Timed Out
'    11011    Bad Request
'    11012    Bad Route
'    11013    TimeToLive Expired Transit
'    11014    TimeToLive Expired Reassembly
'    11015    Parameter Problem
'    11016    Source Quench
'    11017    Option Too Big
'    11018    Bad Destination
'    11032    Negotiating IPSEC
'    11050    General Failure
End Function

Open in new window

Hi kendingo,

Please send me the full path to that file that you are looking for (including the file name) and I will write the optimized script for you that can run against the entire domain with no overhead on speed.

I do a lot of operations on all of the PC's in my domain via scripts and what I do, I first create a collection of all of the PC's and then once all the names are in the collection, before I begin connecting the each of them, I first ping them and if it responds, then I investigate what I need, and then create a log file of all the things I need. Log file is usually CSV so that it can easily be imported to excel for formatting and other manipulation. :-)
kendingoAuthor Commented:
That would be excellent. I hope i can whip something like that out oneday. You are a life saver.

The file name is ucmdmt.sf

It is typically located in the c:\Program Files\DCI folder.
kendingoAuthor Commented:
sorry for the delay hubasan.

That script is exactly what i needed and so easy to modify for some varioations in file name we are working with.

You sir are a gentleman and a saint.
Hehehe...you are welcome. Thanks for the grade and points and good luck.
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.