Solved

VBScript to give computer information based on a file search.

Posted on 2009-04-09
5
1,073 Views
Last Modified: 2012-05-06
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

'

' COMMENT: 

'

'==========================================================================
 

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)

        					Next

    					End If

					Next

				Set colComputer = objWMIService.ExecQuery ("Select * from Win32_ComputerSystem")

					For Each objComputer In colComputer

						WScript.Echo "   User ID:		" & objComputer.UserName

					Next

   				  				

Next
 

WScript.Echo "DONE"

Open in new window

0
Comment
Question by:kendingo
  • 3
  • 2
5 Comments
 
LVL 7

Expert Comment

by:Hubasan
ID: 24111069
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. :-)
0
 
LVL 1

Author Comment

by:kendingo
ID: 24111137
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.
0
 
LVL 7

Accepted Solution

by:
Hubasan earned 500 total points
ID: 24115475
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

Const ADS_SCOPE_SUBTREE = 2
 

'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

oRecordSet.MoveFirst
 

'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"	

			Else

				'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

			Else

				'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

	oRecordSet.MoveNext

Loop
 

'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

  Next

  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"

			Err.Clear

		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)

	Next

	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

	Next

End Function
 

Function Ping(sComputer)

Set oWMI = GetObject(_ 

    "winmgmts:\\.\root\cimv2")

Set colPings = oWMI.ExecQuery _

    ("Select * From Win32_PingStatus where Address = '" & sComputer & "'")
 

For Each oStatus in colPings

	Ping = oStatus.StatusCode

Next
 

'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

0
 
LVL 1

Author Comment

by:kendingo
ID: 24395497
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.
0
 
LVL 7

Expert Comment

by:Hubasan
ID: 24395584
Hehehe...you are welcome. Thanks for the grade and points and good luck.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

This is an addendum to the following article: Acitve Directory based Outlook Signature (http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_24950055.html) The script is fine, and works in normal client-server domains…
Over the years I have built up my own little library of code snippets that I refer to when programming or writing a script.  Many of these have come from the web or adaptations from snippets I find on the Web.  Periodically I add to them when I come…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

747 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now