Solved

VBScript to give computer information based on a file search.

Posted on 2009-04-09
5
1,080 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Technology Partners: 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!

Question has a verified solution.

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

In this article we want to have a look at the directory attributes which are used by Microsoft to store the so called Security Identifiers (SID). These SIDs plays an important role in delegating and granting permissions and in authentication of trus…
Well hello again!  Glad to see you've made it this far without giving up.  In this, the fourth installment of my popular series, I'm going to cover functions and subroutines, what they are, and why they are useful.  Just in case you stumbled onto th…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…
Suggested Courses

734 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