If objFSO.FileExists(somefile) = True Then

I'm verifying whether or not a specific Service file (one (1) .exe file) and it does then the
"If objFSO.FileExists(somefile) = True" should equate to true. However, this is not happening on a good number of the Servers I'm connecting to so I'm wondering why this method isn't working as intended. All of the Servers are remote so in my script I'm using the Locator object as show below. Also, is it necessary to set the objFSO file to "Nothing" upon exit of a loop? Or is there a better way to make sure that the file does exist or do I need to map a Network drive, verify and disconnect that Network drive, etc.?
Thanks for the help Experts, :)
Wallace
----- Setting up WMI Connection using Super User credentials -------
		Set objLocator = CreateObject("WbemScripting.SWbemLocator")
		Set objWMIService = objLocator.ConnectServer(server, "\root\cimv2", strDomain & "\" & strUsername, strPassword)
		objWMIService.Security_.ImpersonationLevel = WbemImpersonationLevelImpersonate
		objWMIService.Security_.AuthenticationLevel = WbemAuthenticationLevelPktPrivacy
------- Portion of my VBScript code where I'm having boolean
evaluation problems ---------
If objFSO.FileExists("\\" & server & "\" & "c$" & strTrgtFile) = True Then
			Set colServices = objWMIService.ExecQuery _
			("SELECT StartMode, State FROM Win32_Service WHERE Name LIKE'" & strService & "'")
			'Check status of OpswareAgent Service
			For Each objService In colServices
				If Not IsNull(objService) Then
					WriteToExcel iRow, server, "Yes", """" & objService.Name & """" & _
									" is currently " & objService.State & " and " & _
										objService.StartMode & ".", "N/A"
				Else
					WriteToExcel iRow, server, "N/A", "Service " & """" & strService & """" & _
												" was not found.", "N/A" 
				End If
			Next
		Else
			WriteToExcel iRow, server, "No", "N/A", "N/A" 
		End If

Open in new window

wally_davisAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

RobSampsonCommented:
Hi Wally,

Can you show us what strTrgtFile contains?

For that to work, it would have to be
strTrgtFile = "\Folder\One(1).exe"

where Folder is a folder on the root of the remote PCs C drive.

You could use
strTrgtFile = "C:\Folder\One(1).exe"

and then use
If objFSO.FileExists("\\" & server & "\" & Replace(strTrgtFile, ":", "$")) = True Then

Regards,

Rob.
wally_davisAuthor Commented:
Hey Rob, here's the strTrgtFile definition:

strTrgtFile = "\Program Files\Opsware\agent\pylibs\watchdog\watchdog.exe"
RobSampsonCommented:
That really should work, but if you try
strTrgtFile = "C:\Program Files\Opsware\agent\pylibs\watchdog\watchdog.exe"

and then use
If objFSO.FileExists("\\" & server & "\" & Replace(strTrgtFile, ":", "$")) = True Then

Does it work any better?

Bear in mind that this will only check for the file with respect to the security access that your user account has.  It will not use any impersonation for the FileExists method.

Regards,

Rob.
Become a CompTIA Certified Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

Brent387Commented:
Set ObjShell = CreateObject("WScript.Shell")
Set ObjFSO = CreateObject("Scripting.FileSystemObject")
strProgramFiles = ObjShell.ExpandEnvironmentStrings("%PROGRAMFILES%")
If objFSO.FileExists(strProgramFiles & "\Opsware\agent\pylibs\watchdog\watchdog.exe") Then
wally_davisAuthor Commented:
Brent387, thank you for your response. However, that string will only check the local server for the watchdog.exe file, not the remote servers.
Rob, I've updated my code with your suggested code. This script is hit and miss. By that I mean, the script will find the file on the first server in my list, the second, third and fourth servers it doesn't find the "watchdog.exe" file (but it does exist) and based on that it doesn't even look the status of my service according to my script.
I also received this strange error message after it was processing the sixth (6th) server: \\SomeServer\C$\Program Files\Opsware\agent\pylibs\watchdog\watchdog.exe
C:\Documents and Settings\walldav\Desktop\2 - WF - New Scripts\Check Se
rvice Version & Status\Check_Existance_HPSA.vbs(193, 2) (null): Call was rejecte
d by callee. i.e. this line --> "Sub WriteToExcel(iRow, srv, hpsa, service, errors)"

So, the FileExists method doesn't seem to be performing the function it should. I'm going to attach the whole script so you can see it. I've ensured my objects were destroyed at the end of the loops and I believe I've set some of the variables to empty string ( "" ) as well. Any help would be most appreciated. This is by far the strangest behaving script to date as far as expected behavior. Thanks.
'Verify existance of HPSA OpswareAgent
'Service file and Service Status

Option Explicit

'On Error Resume Next

Const WbemImpersonationLevelImpersonate = 3
Const WbemAuthenticationLevelPktPrivacy = 6

Dim x, iRow, iCounter, fileContent, totalLineCount
Dim dtSDate, dtStart, dtFinish, dtFDate, dtFTime
Dim strService, strTrgtFile, strServer, strServers, server, strError
Dim strScriptPath, strFullPath, strPingResults, strPrcntgComp
Dim strDomain, strUsername, strPassword, strTestFile, strTestPath
Dim strQDate, strQTime, arrQDate, arrQTime
Dim objExcel, objFSO, objInputFile, objOutputFile, objLocator
Dim objRecCount, objWMIService, objShell, objExec, objService
Dim colServices

'items to identify
strService = "OpswareAgent"
strTrgtFile = "C:\Program Files\Opsware\agent\pylibs\watchdog\watchdog.exe"

Set objFSO = CreateObject("Scripting.FileSystemObject")

strScriptPath = objFSO.GetParentFolderName(WScript.ScriptFullName)
strServers = WScript.Arguments.Item(0)
strFullPath = strScriptPath & "\" & strServers

'Create Excel object and worksheet
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.Workbooks.Add

'Excel header columns, first row
objExcel.Cells(1, 1).Value = "Server Name"
objExcel.Cells(1, 2).Value = "HPSA OpswareAgent ""Watchdog.exe"" file exist?"
objExcel.Cells(1, 3).Value = "OpswareAgent Service Status" 
objExcel.Cells(1, 4).Value = "Errors"

'Excel range and formatting
objExcel.Range("A1:D1").Select
objExcel.Selection.Interior.ColorIndex = 17
objExcel.Selection.Font.ColorIndex = 1
objExcel.Selection.Font.Bold = True
objExcel.Cells.EntireColumn.AutoFit

'start count at row 2
x = 2

'Set objOutputFile = objFSO.OpenTextFile(strScriptPath & "\" & "Check_Existance_HPSA_results.csv", 2, True)
'objOutputFile.WriteLine "Server Name" & "," & "HPSA OpswareAgent ""WatchDog.exe"" file exist?" & _
'	"," & "OpswareAgent Service Status" & "," & "Errors"

If (WScript.Arguments.Count = 1) Then
	If objFSO.FileExists(strFullPath) Then
		strServer = LCase(strServers)
		Set objInputFile = objFSO.OpenTextFile(strServer, 1)
	Else
		WScript.Echo "#############################################################################"
		WScript.Echo "#                                                                           #"
		WScript.Echo "#    Error: Unable to open file " & strServers & " for output.                  #"
		WScript.Echo "#                                                                           #"
		WScript.Echo "#    Important: Verify your script & filename spelling and                  #"
		WScript.Echo "#               that its in the same path as your script.                   #"
		WScript.Echo "#                                                                           #"				
		WScript.Echo "#############################################################################"
		WScript.Quit
	End If
Else
	WScript.Echo "#############################################################################"
	WScript.Echo "#                                                                           #"
	WScript.Echo "#    Usage: Check_Existance_HPSA.vbs serverlist.txt                         #"
	WScript.Echo "#                                                                           #"		
	WScript.Echo "#    Important: Verify your script & filename spelling and                  #"
	WScript.Echo "#               that its in the same path as your script.                   #"	
	WScript.Echo "#                                                                           #"				
	WScript.Echo "#############################################################################"
	WScript.Quit
End If

strDomain = InputBox("Please enter your Domain name: ")
strUsername = InputBox("Please enter your Username: ")
strPassword = InputBox("Please enter your Password: ")

'Echo Script Start time
dtSDate = Date
dtStart = Time
WScript.Echo "Please be patient. Script is processing your request...." & vbCrLf & vbCrLf
WScript.Echo "Script Start Time: " & dtSDate & " " & dtStart

'Count total records from File
'This will display "Processing Record: xx of xxx
Set objRecCount = CreateObject("Scripting.FileSystemObject")
Set fileContent = objRecCount.OpenTextFile(strFullPath, 1)
totalLineCount = UBound(Split(fileContent.ReadAll, vbLf)) + 1
fileContent.Close
Set fileContent = Nothing
Set objRecCount = Nothing

'Pass In Server name, Ping It, Call CheckHpsaStatus
Do Until objInputFile.AtEndOfLine
	strServer = ""
	strServer = UCase(objInputFile.ReadLine())
	
	Set objShell = CreateObject("WScript.Shell")
	Set objExec = objShell.Exec("Ping -n 2 -w 500 " & strServer)
	strPingResults = LCase(objExec.StdOut.ReadAll)
	
	'Perform ping and check for hpsa
	If InStr(strPingResults, "reply from") Then
		iRow = x
		
		Call CheckHpsaStatus(iRow, strServer)
		
		If Err.Number <> 0 Then
			strError = Err.Description
			WriteToExcel iRow, strServer, "N/A", "N/A", "Error Description: " & strError & "." & _
												" Error number: " & Err.Number & "."
			Err.Clear()
		End If
	Else
		iRow = x
		WriteToExcel iRow, strServer, "N/A", "N/A", "Ping failed."
	End If
	
	x = x + 1
	
	'Output current process status
	'to DOS Cmd shell
	iCounter = iCounter + 1
	WScript.Echo "Processing record " & iCounter & " of " & totalLineCount
	strPrcntgComp = (iCounter / totalLineCount) * 100
	strPrcntgComp = Left(strPrcntgComp, 5)
	WScript.Echo "Percent Complete: " & strPrcntgComp & "%"
	WScript.Echo
	
	Set objShell = Nothing
	Set objExec = Nothing
Loop

strQDate = Date
arrQDate = Split(strQDate, "/")
strQDate = arrQDate(0) & "-" & arrQDate(1) & "-" & arrQDate(2)
strQTime = Time
arrQTime = Split(strQTime, ":")
strQTime = arrQTime(0) & "-" & arrQTime(1) & "-" & arrQTime(2)

objExcel.ActiveWorkbook.SaveAs strScriptPath & "\" & _
	"Check_Existance_HPSA_results_" & strQDate & "_" & strQTime & "_" & ".xlsx" 
objExcel.Quit

'Verify existance of HPSA OpswareAgent
'Service file and Service Status
Sub CheckHpsaStatus(iRow, server)
		Set objLocator = CreateObject("WbemScripting.SWbemLocator")
		Set objWMIService = objLocator.ConnectServer(server, "\root\cimv2", strDomain & "\" & strUsername, strPassword)
		objWMIService.Security_.ImpersonationLevel = WbemImpersonationLevelImpersonate
		objWMIService.Security_.AuthenticationLevel = WbemAuthenticationLevelPktPrivacy

		If Err Then
			Exit Sub
		End If
		
		'Determine if OpswareAgent Service file exist
		WScript.Echo ("\\" & server & "\" & Replace(strTrgtFile, ":", "$"))
		If objFSO.FileExists("\\" & server & "\" & Replace(strTrgtFile, ":", "$")) = True Then
			Set colServices = objWMIService.ExecQuery _
			("SELECT StartMode, State FROM Win32_Service WHERE Name LIKE'" & strService & "'")
			'Check status of OpswareAgent Service
			For Each objService In colServices
				If Not IsNull(objService) Then
					WriteToExcel iRow, server, "Yes", """" & objService.Name & """" & _
									" is currently " & objService.State & " and " & _
										objService.StartMode & ".", "N/A"
				Else
					WriteToExcel iRow, server, "N/A", "Service " & """" & strService & """" & _
												" was not found.", "N/A" 
				End If
			Next
		Else
			WriteToExcel iRow, server, "No", "N/A", "N/A" 
		End If
		
		Set objLocator = Nothing
		Set objWMIService = Nothing
		Set colServices = Nothing
		server = ""
End Sub

Sub WriteToExcel(iRow, srv, hpsa, service, errors)
	objExcel.Cells(iRow, 1).Value = srv
	objExcel.Cells(iRow, 2).Value = hpsa
	objExcel.Cells(iRow, 3).Value = service
	objExcel.Cells(iRow, 4).Value = errors
End Sub

'Function to Convert the span time of "seconds
'to HH:MM:SS
Function TimeSpan(dt1, dt2)
	Dim strLenDt1, strLenDt2
	Dim seconds, minutes, hours 
	strLenDt1 = Len(dt1)
	strLenDt2 = Len(dt2)
	dt1 = Trim(Left(dt1, strLenDt1 - 3))
	dt2 = Trim(Left(dt2, strLenDt2 - 3))
	If IsDate(dt1) And IsDate(dt2) = False Then
		TimeSpan = "00:00:00"
		Exit Function
	End If
		seconds = Abs(DateDiff("s", dt1, dt2))
		minutes = seconds \ 60
		hours = minutes \ 60
		seconds = seconds Mod 60
		minutes = minutes Mod 60
		
		'If Len(hours) = 1 Then hours = 0 & hours
		
		TimeSpan = hours & " Hour(s), " & _
			Right("00" & minutes, 2) & " Minute(s), " & _
			Right("00" & seconds, 2) & " Second(s)"
End Function

'Echo Script Finish time, Total Processing time 
'and Total Records proccessed upon script completion
dtFDate = Date
dtFTime = Time
WScript.Echo
WScript.Echo "Script Finish Time: " & dtFDate & " " & dtFTime & vbCrLf
WScript.Echo "Total Processing Time: " & TimeSpan(dtStart, dtFTime)
WScript.Echo "Total Records processed: " & iCounter & " of " & totalLineCount
WScript.Echo "Percent Completed: " & strPrcntgComp & "%"

WScript.Echo "" & vbCrLf
WScript.Echo "######################################################################" & vbCrLf & _
			 "#                                                                    #" & vbCrLf & _
			 "# PROCESSING OF THE Check_Existance_HPSA.vbs HAS COMPLETED!!         #" & vbCrLf & _
			 "#                                                                    #" & vbCrLf & _
			 "# Output file: Check_Existance_HPSA_results.xlsx                      #" & vbCrLf & _
			 "#                                                                    #" & vbCrLf & _
			 "######################################################################"
WScript.Quit

Open in new window

wally_davisAuthor Commented:
FYI, Now, for a test, I to to Start, Run and type in this:
\\SERVER_AB\c$\Program Files\Opsware\agent\pylibs\watchdog
I get an error message that says "Windows cannot find
'\\SERVER_AB\c$\Program'. Make sure you typed the name correctly then try again..."
BUT, IF I TYPE IN "\\SERVER_AB\c$", it will prompt me for my Domain\Username and password, then I can connect and then traverse through the folder structure to find that in fact the file exists.
I'm wondering if Brent387 is onto something. It sounds like I need to break out the folder structure and/or connect it by concatenating two different strings. I have to run to a two hour meeting but will check back here and try a few other things myself. Thanks.
wally_davisAuthor Commented:
Update. Based on my previous Comment thread, I ran a test to see what would happen.
I ran the script against 10 servers. The first five (5) that I had connected to using UNC Path previously, you know, \\ServerName\c$. Once I connected to the Server, I received a prompt for my credentials and logged in and of course,my credentials are stored on each remote server I connected to in this manner.
So, for the first 5 servers, my script was able to retrieve data and output to Excel. The next 5 servers failed. I connected to the 10th Server in the list using the UNC \\ServerName\c$ and logged in with my credentials. I re-ran the script and voila, the 1st - 5th Servers were successful, 6th - 9th Servers failed and you guessed it, the 10th Server passed and I received data.
My question is, is there a second method I have to use to connect to the Server outside of the method I am currently using in my Script that is already passing in Domain, Username and Password data? I've never seen it where you have to provide credentials to verify a file on another server. Or maybe its that I've never used FileExists method in this manner.
RobSampsonCommented:
>> BUT, IF I TYPE IN "\\SERVER_AB\c$", it will prompt me for my Domain\Username and password, then I can connect

This appears to be a security issue, as I alluded when I said
>> Bear in mind that this will only check for the file with respect to the security access that your user account has.  It will not use any impersonation for the FileExists method.

When Windows is asking you for alternate credentials, the current user is unable to access the share.  So, what we might be able to do is use cmdkey.exe to add the credentials for authentication to that server.

Try this out.

If server 6 to 9 require a different set of credentials, we'll have to work that in somehow.

Regards,

Rob.
'Verify existance of HPSA OpswareAgent
'Service file and Service Status

Option Explicit

'On Error Resume Next

Const WbemImpersonationLevelImpersonate = 3
Const WbemAuthenticationLevelPktPrivacy = 6

Dim x, iRow, iCounter, fileContent, totalLineCount
Dim dtSDate, dtStart, dtFinish, dtFDate, dtFTime
Dim strService, strTrgtFile, strServer, strServers, server, strError
Dim strScriptPath, strFullPath, strPingResults, strPrcntgComp
Dim strDomain, strUsername, strPassword, strTestFile, strTestPath
Dim strQDate, strQTime, arrQDate, arrQTime
Dim objExcel, objFSO, objInputFile, objOutputFile, objLocator
Dim objRecCount, objWMIService, objShell, objExec, objService
Dim colServices

'items to identify
strService = "OpswareAgent"
strTrgtFile = "C:\Program Files\Opsware\agent\pylibs\watchdog\watchdog.exe"

Set objFSO = CreateObject("Scripting.FileSystemObject")

strScriptPath = objFSO.GetParentFolderName(WScript.ScriptFullName)
strServers = WScript.Arguments.Item(0)
strFullPath = strScriptPath & "\" & strServers

'Create Excel object and worksheet
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.Workbooks.Add

'Excel header columns, first row
objExcel.Cells(1, 1).Value = "Server Name"
objExcel.Cells(1, 2).Value = "HPSA OpswareAgent ""Watchdog.exe"" file exist?"
objExcel.Cells(1, 3).Value = "OpswareAgent Service Status" 
objExcel.Cells(1, 4).Value = "Errors"

'Excel range and formatting
objExcel.Range("A1:D1").Select
objExcel.Selection.Interior.ColorIndex = 17
objExcel.Selection.Font.ColorIndex = 1
objExcel.Selection.Font.Bold = True
objExcel.Cells.EntireColumn.AutoFit

'start count at row 2
x = 2

'Set objOutputFile = objFSO.OpenTextFile(strScriptPath & "\" & "Check_Existance_HPSA_results.csv", 2, True)
'objOutputFile.WriteLine "Server Name" & "," & "HPSA OpswareAgent ""WatchDog.exe"" file exist?" & _
'	"," & "OpswareAgent Service Status" & "," & "Errors"

If (WScript.Arguments.Count = 1) Then
	If objFSO.FileExists(strFullPath) Then
		strServer = LCase(strServers)
		Set objInputFile = objFSO.OpenTextFile(strServer, 1)
	Else
		WScript.Echo "#############################################################################"
		WScript.Echo "#                                                                           #"
		WScript.Echo "#    Error: Unable to open file " & strServers & " for output.                  #"
		WScript.Echo "#                                                                           #"
		WScript.Echo "#    Important: Verify your script & filename spelling and                  #"
		WScript.Echo "#               that its in the same path as your script.                   #"
		WScript.Echo "#                                                                           #"				
		WScript.Echo "#############################################################################"
		WScript.Quit
	End If
Else
	WScript.Echo "#############################################################################"
	WScript.Echo "#                                                                           #"
	WScript.Echo "#    Usage: Check_Existance_HPSA.vbs serverlist.txt                         #"
	WScript.Echo "#                                                                           #"		
	WScript.Echo "#    Important: Verify your script & filename spelling and                  #"
	WScript.Echo "#               that its in the same path as your script.                   #"	
	WScript.Echo "#                                                                           #"				
	WScript.Echo "#############################################################################"
	WScript.Quit
End If

strDomain = InputBox("Please enter your Domain name: ")
strUsername = InputBox("Please enter your Username: ")
strPassword = InputBox("Please enter your Password: ")

'Echo Script Start time
dtSDate = Date
dtStart = Time
WScript.Echo "Please be patient. Script is processing your request...." & vbCrLf & vbCrLf
WScript.Echo "Script Start Time: " & dtSDate & " " & dtStart

'Count total records from File
'This will display "Processing Record: xx of xxx
Set objRecCount = CreateObject("Scripting.FileSystemObject")
Set fileContent = objRecCount.OpenTextFile(strFullPath, 1)
totalLineCount = UBound(Split(fileContent.ReadAll, vbLf)) + 1
fileContent.Close
Set fileContent = Nothing
Set objRecCount = Nothing

strCommand = "cmd /c cmdkey /add:* /user:" & strDomain & "\" & strUsername & " /pass:" & strPassword 
Set objShell = CreateObject("WScript.Shell")
objShell.Run strCommand, 0, True

'Pass In Server name, Ping It, Call CheckHpsaStatus
Do Until objInputFile.AtEndOfLine
	strServer = ""
	strServer = UCase(objInputFile.ReadLine())
	
	Set objShell = CreateObject("WScript.Shell")
	Set objExec = objShell.Exec("Ping -n 2 -w 500 " & strServer)
	strPingResults = LCase(objExec.StdOut.ReadAll)
	
	'Perform ping and check for hpsa
	If InStr(strPingResults, "reply from") Then
		iRow = x
		
		Call CheckHpsaStatus(iRow, strServer)
		
		If Err.Number <> 0 Then
			strError = Err.Description
			WriteToExcel iRow, strServer, "N/A", "N/A", "Error Description: " & strError & "." & _
												" Error number: " & Err.Number & "."
			Err.Clear()
		End If
	Else
		iRow = x
		WriteToExcel iRow, strServer, "N/A", "N/A", "Ping failed."
	End If
	
	x = x + 1
	
	'Output current process status
	'to DOS Cmd shell
	iCounter = iCounter + 1
	WScript.Echo "Processing record " & iCounter & " of " & totalLineCount
	strPrcntgComp = (iCounter / totalLineCount) * 100
	strPrcntgComp = Left(strPrcntgComp, 5)
	WScript.Echo "Percent Complete: " & strPrcntgComp & "%"
	WScript.Echo
	
	Set objShell = Nothing
	Set objExec = Nothing
Loop

strCommand = "cmd /c cmdkey /delete:*"
objShell.Run strCommand, 0, True

strQDate = Date
arrQDate = Split(strQDate, "/")
strQDate = arrQDate(0) & "-" & arrQDate(1) & "-" & arrQDate(2)
strQTime = Time
arrQTime = Split(strQTime, ":")
strQTime = arrQTime(0) & "-" & arrQTime(1) & "-" & arrQTime(2)

objExcel.ActiveWorkbook.SaveAs strScriptPath & "\" & _
	"Check_Existance_HPSA_results_" & strQDate & "_" & strQTime & "_" & ".xlsx" 
objExcel.Quit

'Verify existance of HPSA OpswareAgent
'Service file and Service Status
Sub CheckHpsaStatus(iRow, server)
		Set objLocator = CreateObject("WbemScripting.SWbemLocator")
		Set objWMIService = objLocator.ConnectServer(server, "\root\cimv2", strDomain & "\" & strUsername, strPassword)
		objWMIService.Security_.ImpersonationLevel = WbemImpersonationLevelImpersonate
		objWMIService.Security_.AuthenticationLevel = WbemAuthenticationLevelPktPrivacy

		If Err Then
			Exit Sub
		End If
		
		'Determine if OpswareAgent Service file exist
		WScript.Echo ("\\" & server & "\" & Replace(strTrgtFile, ":", "$"))
		If objFSO.FileExists("\\" & server & "\" & Replace(strTrgtFile, ":", "$")) = True Then
			Set colServices = objWMIService.ExecQuery _
			("SELECT StartMode, State FROM Win32_Service WHERE Name LIKE'" & strService & "'")
			'Check status of OpswareAgent Service
			For Each objService In colServices
				If Not IsNull(objService) Then
					WriteToExcel iRow, server, "Yes", """" & objService.Name & """" & _
									" is currently " & objService.State & " and " & _
										objService.StartMode & ".", "N/A"
				Else
					WriteToExcel iRow, server, "N/A", "Service " & """" & strService & """" & _
												" was not found.", "N/A" 
				End If
			Next
		Else
			WriteToExcel iRow, server, "No", "N/A", "N/A" 
		End If
		
		Set objLocator = Nothing
		Set objWMIService = Nothing
		Set colServices = Nothing
		server = ""
End Sub

Sub WriteToExcel(iRow, srv, hpsa, service, errors)
	objExcel.Cells(iRow, 1).Value = srv
	objExcel.Cells(iRow, 2).Value = hpsa
	objExcel.Cells(iRow, 3).Value = service
	objExcel.Cells(iRow, 4).Value = errors
End Sub

'Function to Convert the span time of "seconds
'to HH:MM:SS
Function TimeSpan(dt1, dt2)
	Dim strLenDt1, strLenDt2
	Dim seconds, minutes, hours 
	strLenDt1 = Len(dt1)
	strLenDt2 = Len(dt2)
	dt1 = Trim(Left(dt1, strLenDt1 - 3))
	dt2 = Trim(Left(dt2, strLenDt2 - 3))
	If IsDate(dt1) And IsDate(dt2) = False Then
		TimeSpan = "00:00:00"
		Exit Function
	End If
		seconds = Abs(DateDiff("s", dt1, dt2))
		minutes = seconds \ 60
		hours = minutes \ 60
		seconds = seconds Mod 60
		minutes = minutes Mod 60
		
		'If Len(hours) = 1 Then hours = 0 & hours
		
		TimeSpan = hours & " Hour(s), " & _
			Right("00" & minutes, 2) & " Minute(s), " & _
			Right("00" & seconds, 2) & " Second(s)"
End Function

'Echo Script Finish time, Total Processing time 
'and Total Records proccessed upon script completion
dtFDate = Date
dtFTime = Time
WScript.Echo
WScript.Echo "Script Finish Time: " & dtFDate & " " & dtFTime & vbCrLf
WScript.Echo "Total Processing Time: " & TimeSpan(dtStart, dtFTime)
WScript.Echo "Total Records processed: " & iCounter & " of " & totalLineCount
WScript.Echo "Percent Completed: " & strPrcntgComp & "%"

WScript.Echo "" & vbCrLf
WScript.Echo "######################################################################" & vbCrLf & _
			 "#                                                                    #" & vbCrLf & _
			 "# PROCESSING OF THE Check_Existance_HPSA.vbs HAS COMPLETED!!         #" & vbCrLf & _
			 "#                                                                    #" & vbCrLf & _
			 "# Output file: Check_Existance_HPSA_results.xlsx                      #" & vbCrLf & _
			 "#                                                                    #" & vbCrLf & _
			 "######################################################################"
WScript.Quit

Open in new window

wally_davisAuthor Commented:
Rob, thank you for the explanation. I decided to test the "cmdkey.exe" from the Command prompt. I'm getting the following message: CMDKEY: Credentials cannot be saved from this logon session.

I needed to verify it because the script was failing right off from the beginning. I've googled it and there seems to be no metion of anyone running into this issue. I'm attempting to run this from my XP Laptop and the cmdkey.exe file was copied to my Laptop from Windows 2003 Server x32. I also tried the Run As against the Cmd shell and that didn't help either.
RobSampsonCommented:
Hmmm, are you logged in as a regular user account (and / or the same account that you're running the script as)?

Can you try
cmdkey /add:YOURDOMAIN\* /user:YOUROMDAIN\Username /pass:password

That worked on my system, because I already had credentials for Passport.NET\*, and therefore could not use just *.

If you go to Control Panel --> User Accounts --> Advanced tab, then click the Manage Passwors button
I was only able to add MYDOMAIN\*

If that does work, change this line:
strCommand = "cmd /c cmdkey /add:* /user:" & strDomain & "\" & strUsername & " /pass:" & strPassword

to this
strCommand = "cmd /c cmdkey /add:" & strDomain & "\* /user:" & strDomain & "\" & strUsername & " /pass:" & strPassword

and change this line:
strCommand = "cmd /c cmdkey /delete:*"

to this:
strCommand = "cmd /c cmdkey /delete:" & strDomain &"\*"


Regards,

Rob.
wally_davisAuthor Commented:
Hey Rob, I just woke up. It's just about 6:00 a.m. here in Arizona. I did try your examples and I'm still getting that same error and therefore no information is getting stored. I even have Administrative rights on this laptop. Is it possible that the Windows 2003 Server "cmdkey" version is incompatible on XP Pro SP3 or that some Network GPO is in place preventing this thing from running? I was going to download what appeared to be a more current version but I got a Virus on my machine and backed out of that. I'll check back in about an hour.
wally_davisAuthor Commented:
Rob, as you've already seen, this part of my code allows me to store my Super User account to access any and all servers:
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
            Set objWMIService = objLocator.ConnectServer(server, "\root\cimv2", strDomain & "\" & strUsername, strPassword)
            objWMIService.Security_.ImpersonationLevel = WbemImpersonationLevelImpersonate
            objWMIService.Security_.AuthenticationLevel = WbemAuthenticationLevelPktPrivacy
wally_davisAuthor Commented:
Rob, I've even tried to run the cmdkey on the Windows 2003 Server itself and I still get the message "CMDKEY: Credentials cannot be saved from this logon session". My own manager has never used it and I'm not even certain why this utility won't run. Again, I'm not sure if this file is the current version --> ( I have 2/17/2007 12:31AM). I also can't download the CMDKey 1.01 version because this site is blocked from within our corporate network and says it has a virus associated with it.
I'm going to look at the WScript.Network class to see if that will help. I'm getting nothing but dead ends with cmdkey. I just think there's a possiblity our Network Guru's are restriction happy around here. BLOCK EVERYTHING. lol.
wally_davisAuthor Commented:
ok, I'm one step closer. Here's what I have but now I need to figure out how to verify that the Network path exists just in case "it doesn't" so need to handle that. I've already run into that scenario.
Dim objNetwork
Set objNetwork = CreateObject("WScript.Network")
'Setup remote drive
objNetwork.MapNetworkDrive "R:", "\\" & strServer & "\" & "c$", False, strUsername, strPassword
'disconnect remote drive
objNetwork.RemoveNetworkDrive "R:", True, True
wally_davisAuthor Commented:
ok Rob, I implemented the If Err = 0 Then 'Do This' Else 'Do That'. That works fine, but, I have one issue
with respect to Errors <> 0.
For instance, when I have the script write errors to Excel, specifically for Err.Description, in excel,  at the end of string that is written to a Cell in the spreadsheet, there's this little question mark in a small, small box. So, there's some sort of ASCII character that is getting padded and it is causing the script to skip to rows in Excel and start writing the next servers status. I tried to use Trim(Err.Description) but that didn't help at all. Is there another approach to cleanup anything added to an Excel "Cell" that isn't String data?
RobSampsonCommented:
Wally, the version on cmdkey.exe I have on my Windows XP Pro SP3 is 5.2.3790.1830 created on Friday, 15 June 2007, 5:20:20 PM.

It works fine.  I have attached it anyway.

Did you try the manual approach via Control Panel --> User Accounts?

As far as writing to the next row goes, I've replaced x = x + 1 with objExcel.Cells(65536, "A").End(xlUp).Row + 1
That makes sure that you're always writing to the next available row on each iteration through the loop.

Regards,

Rob.

'Verify existance of HPSA OpswareAgent
'Service file and Service Status

Option Explicit

'On Error Resume Next

Const WbemImpersonationLevelImpersonate = 3
Const WbemAuthenticationLevelPktPrivacy = 6
Const xlUp = -4162

Dim x, iRow, iCounter, fileContent, totalLineCount
Dim dtSDate, dtStart, dtFinish, dtFDate, dtFTime
Dim strService, strTrgtFile, strServer, strServers, server, strError
Dim strScriptPath, strFullPath, strPingResults, strPrcntgComp
Dim strDomain, strUsername, strPassword, strTestFile, strTestPath
Dim strQDate, strQTime, arrQDate, arrQTime
Dim objExcel, objFSO, objInputFile, objOutputFile, objLocator
Dim objRecCount, objWMIService, objShell, objExec, objService
Dim colServices

'items to identify
strService = "OpswareAgent"
strTrgtFile = "C:\Program Files\Opsware\agent\pylibs\watchdog\watchdog.exe"

Set objFSO = CreateObject("Scripting.FileSystemObject")

strScriptPath = objFSO.GetParentFolderName(WScript.ScriptFullName)
strServers = WScript.Arguments.Item(0)
strFullPath = strScriptPath & "\" & strServers

'Create Excel object and worksheet
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.Workbooks.Add

'Excel header columns, first row
objExcel.Cells(1, 1).Value = "Server Name"
objExcel.Cells(1, 2).Value = "HPSA OpswareAgent ""Watchdog.exe"" file exist?"
objExcel.Cells(1, 3).Value = "OpswareAgent Service Status" 
objExcel.Cells(1, 4).Value = "Errors"

'Excel range and formatting
objExcel.Range("A1:D1").Select
objExcel.Selection.Interior.ColorIndex = 17
objExcel.Selection.Font.ColorIndex = 1
objExcel.Selection.Font.Bold = True
objExcel.Cells.EntireColumn.AutoFit

'start count at row 2
'x = 2

'Set objOutputFile = objFSO.OpenTextFile(strScriptPath & "\" & "Check_Existance_HPSA_results.csv", 2, True)
'objOutputFile.WriteLine "Server Name" & "," & "HPSA OpswareAgent ""WatchDog.exe"" file exist?" & _
'	"," & "OpswareAgent Service Status" & "," & "Errors"

If (WScript.Arguments.Count = 1) Then
	If objFSO.FileExists(strFullPath) Then
		strServer = LCase(strServers)
		Set objInputFile = objFSO.OpenTextFile(strServer, 1)
	Else
		WScript.Echo "#############################################################################"
		WScript.Echo "#                                                                           #"
		WScript.Echo "#    Error: Unable to open file " & strServers & " for output.                  #"
		WScript.Echo "#                                                                           #"
		WScript.Echo "#    Important: Verify your script & filename spelling and                  #"
		WScript.Echo "#               that its in the same path as your script.                   #"
		WScript.Echo "#                                                                           #"				
		WScript.Echo "#############################################################################"
		WScript.Quit
	End If
Else
	WScript.Echo "#############################################################################"
	WScript.Echo "#                                                                           #"
	WScript.Echo "#    Usage: Check_Existance_HPSA.vbs serverlist.txt                         #"
	WScript.Echo "#                                                                           #"		
	WScript.Echo "#    Important: Verify your script & filename spelling and                  #"
	WScript.Echo "#               that its in the same path as your script.                   #"	
	WScript.Echo "#                                                                           #"				
	WScript.Echo "#############################################################################"
	WScript.Quit
End If

strDomain = InputBox("Please enter your Domain name: ")
strUsername = InputBox("Please enter your Username: ")
strPassword = InputBox("Please enter your Password: ")

'Echo Script Start time
dtSDate = Date
dtStart = Time
WScript.Echo "Please be patient. Script is processing your request...." & vbCrLf & vbCrLf
WScript.Echo "Script Start Time: " & dtSDate & " " & dtStart

'Count total records from File
'This will display "Processing Record: xx of xxx
Set objRecCount = CreateObject("Scripting.FileSystemObject")
Set fileContent = objRecCount.OpenTextFile(strFullPath, 1)
totalLineCount = UBound(Split(fileContent.ReadAll, vbLf)) + 1
fileContent.Close
Set fileContent = Nothing
Set objRecCount = Nothing

strCommand = "cmd /c cmdkey /add:" & strDomain & "\* /user:" & strDomain & "\" & strUsername & " /pass:" & strPassword 
Set objShell = CreateObject("WScript.Shell")
objShell.Run strCommand, 0, True

'Pass In Server name, Ping It, Call CheckHpsaStatus
Do Until objInputFile.AtEndOfLine
	' start at the next blank row
	x = objExcel.Cells(65536, "A").End(xlUp).Row + 1

	strServer = ""
	strServer = UCase(objInputFile.ReadLine())
	
	Set objShell = CreateObject("WScript.Shell")
	Set objExec = objShell.Exec("Ping -n 2 -w 500 " & strServer)
	strPingResults = LCase(objExec.StdOut.ReadAll)
	
	'Perform ping and check for hpsa
	If InStr(strPingResults, "reply from") Then
		iRow = x
		
		Call CheckHpsaStatus(iRow, strServer)
		
		If Err.Number <> 0 Then
			strError = Err.Description
			WriteToExcel iRow, strServer, "N/A", "N/A", "Error Description: " & strError & "." & _
												" Error number: " & Err.Number & "."
			Err.Clear()
		End If
	Else
		iRow = x
		WriteToExcel iRow, strServer, "N/A", "N/A", "Ping failed."
	End If
	
	'x = x + 1
	
	'Output current process status
	'to DOS Cmd shell
	iCounter = iCounter + 1
	WScript.Echo "Processing record " & iCounter & " of " & totalLineCount
	strPrcntgComp = (iCounter / totalLineCount) * 100
	strPrcntgComp = Left(strPrcntgComp, 5)
	WScript.Echo "Percent Complete: " & strPrcntgComp & "%"
	WScript.Echo
	
	Set objShell = Nothing
	Set objExec = Nothing
Loop

strCommand = "cmd /c cmdkey /delete:" & strDomain & "\*"
objShell.Run strCommand, 0, True

strQDate = Date
arrQDate = Split(strQDate, "/")
strQDate = arrQDate(0) & "-" & arrQDate(1) & "-" & arrQDate(2)
strQTime = Time
arrQTime = Split(strQTime, ":")
strQTime = arrQTime(0) & "-" & arrQTime(1) & "-" & arrQTime(2)

objExcel.ActiveWorkbook.SaveAs strScriptPath & "\" & _
	"Check_Existance_HPSA_results_" & strQDate & "_" & strQTime & "_" & ".xlsx" 
objExcel.Quit

'Verify existance of HPSA OpswareAgent
'Service file and Service Status
Sub CheckHpsaStatus(iRow, server)
		Set objLocator = CreateObject("WbemScripting.SWbemLocator")
		Set objWMIService = objLocator.ConnectServer(server, "\root\cimv2", strDomain & "\" & strUsername, strPassword)
		objWMIService.Security_.ImpersonationLevel = WbemImpersonationLevelImpersonate
		objWMIService.Security_.AuthenticationLevel = WbemAuthenticationLevelPktPrivacy

		If Err Then
			Exit Sub
		End If
		
		'Determine if OpswareAgent Service file exist
		WScript.Echo ("\\" & server & "\" & Replace(strTrgtFile, ":", "$"))
		If objFSO.FileExists("\\" & server & "\" & Replace(strTrgtFile, ":", "$")) = True Then
			Set colServices = objWMIService.ExecQuery _
			("SELECT StartMode, State FROM Win32_Service WHERE Name LIKE'" & strService & "'")
			'Check status of OpswareAgent Service
			For Each objService In colServices
				If Not IsNull(objService) Then
					WriteToExcel iRow, server, "Yes", """" & objService.Name & """" & _
									" is currently " & objService.State & " and " & _
										objService.StartMode & ".", "N/A"
				Else
					WriteToExcel iRow, server, "N/A", "Service " & """" & strService & """" & _
												" was not found.", "N/A" 
				End If
			Next
		Else
			WriteToExcel iRow, server, "No", "N/A", "N/A" 
		End If
		
		Set objLocator = Nothing
		Set objWMIService = Nothing
		Set colServices = Nothing
		server = ""
End Sub

Sub WriteToExcel(iRow, srv, hpsa, service, errors)
	objExcel.Cells(iRow, 1).Value = srv
	objExcel.Cells(iRow, 2).Value = hpsa
	objExcel.Cells(iRow, 3).Value = service
	objExcel.Cells(iRow, 4).Value = errors
End Sub

'Function to Convert the span time of "seconds
'to HH:MM:SS
Function TimeSpan(dt1, dt2)
	Dim strLenDt1, strLenDt2
	Dim seconds, minutes, hours 
	strLenDt1 = Len(dt1)
	strLenDt2 = Len(dt2)
	dt1 = Trim(Left(dt1, strLenDt1 - 3))
	dt2 = Trim(Left(dt2, strLenDt2 - 3))
	If IsDate(dt1) And IsDate(dt2) = False Then
		TimeSpan = "00:00:00"
		Exit Function
	End If
		seconds = Abs(DateDiff("s", dt1, dt2))
		minutes = seconds \ 60
		hours = minutes \ 60
		seconds = seconds Mod 60
		minutes = minutes Mod 60
		
		'If Len(hours) = 1 Then hours = 0 & hours
		
		TimeSpan = hours & " Hour(s), " & _
			Right("00" & minutes, 2) & " Minute(s), " & _
			Right("00" & seconds, 2) & " Second(s)"
End Function

'Echo Script Finish time, Total Processing time 
'and Total Records proccessed upon script completion
dtFDate = Date
dtFTime = Time
WScript.Echo
WScript.Echo "Script Finish Time: " & dtFDate & " " & dtFTime & vbCrLf
WScript.Echo "Total Processing Time: " & TimeSpan(dtStart, dtFTime)
WScript.Echo "Total Records processed: " & iCounter & " of " & totalLineCount
WScript.Echo "Percent Completed: " & strPrcntgComp & "%"

WScript.Echo "" & vbCrLf
WScript.Echo "######################################################################" & vbCrLf & _
			 "#                                                                    #" & vbCrLf & _
			 "# PROCESSING OF THE Check_Existance_HPSA.vbs HAS COMPLETED!!         #" & vbCrLf & _
			 "#                                                                    #" & vbCrLf & _
			 "# Output file: Check_Existance_HPSA_results.xlsx                      #" & vbCrLf & _
			 "#                                                                    #" & vbCrLf & _
			 "######################################################################"
WScript.Quit

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
wally_davisAuthor Commented:
Code now works. See code below.


'Created 4/21/2010 - Wallace Davis
'Verify existance of HPSA OpswareAgent
'Service file and Service Status

Option Explicit

On Error Resume Next

Const WbemImpersonationLevelImpersonate = 3
Const WbemAuthenticationLevelPktPrivacy = 6

Dim x, iRow, iCounter, fileContent, totalLineCount
Dim dtSDate, dtStart, dtFinish, dtFDate, dtFTime
Dim strService, strTrgtFile, strServer, strServers, server, strError
Dim strScriptPath, strFullPath, strPingResults, strPrcntgComp, strErrDescrip
Dim strDomain, strUsername, strPassword, strTestFile, strTestPath
Dim strCommand, strCommand2, strQDate, strQTime, arrQDate, arrQTime
Dim objExcel, objFSO, objInputFile, objOutputFile, objLocator, objNetwork
Dim objRecCount, objWMIService, objShell, objExec, objService
Dim colServices

'Service and Service file to be verified
strService = "OpswareAgent"
strTrgtFile = "R:\Progra~1\Opsware\agent\pylibs\watchdog\watchdog.exe"

Set objFSO = CreateObject("Scripting.FileSystemObject")

strScriptPath = objFSO.GetParentFolderName(WScript.ScriptFullName)

If (WScript.Arguments.Count > 0) Then
	strServers = WScript.Arguments.Item(0)
	strFullPath = strScriptPath & "\" & strServers
	
	If objFSO.FileExists(strFullPath) Then
		strServer = LCase(strServers)
		Set objInputFile = objFSO.OpenTextFile(strServer, 1)
	Else
		WScript.Echo "#############################################################################"
		WScript.Echo "#                                                                           #"
		WScript.Echo "#    Error: Unable to open file " & strServers & " for output.                  #"
		WScript.Echo "#                                                                           #"
		WScript.Echo "#    Important: Verify your script & filename spelling and                  #"
		WScript.Echo "#               that its in the same path as your script.                   #"
		WScript.Echo "#                                                                           #"				
		WScript.Echo "#############################################################################"
		WScript.Quit
	End If
Else
	WScript.Echo "#############################################################################"
	WScript.Echo "#                                                                           #"
	WScript.Echo "#    Usage: Check_Existance_HPSA.vbs serverlist.txt                         #"
	WScript.Echo "#                                                                           #"		
	WScript.Echo "#    Important: Verify your script & filename spelling and                  #"
	WScript.Echo "#               that its in the same path as your script.                   #"	
	WScript.Echo "#                                                                           #"				
	WScript.Echo "#############################################################################"
	WScript.Quit
End If

'Create Excel object and worksheet
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.Workbooks.Add

'Excel header columns, first row
objExcel.Cells(1, 1).Value = "Server Name"
objExcel.Cells(1, 2).Value = "HPSA OpswareAgent ""Watchdog.exe"" file exist?"
objExcel.Cells(1, 3).Value = "OpswareAgent Service Status" 
objExcel.Cells(1, 4).Value = "Errors"

'Excel range and formatting
objExcel.Range("A1:D1").Select
objExcel.Selection.Interior.ColorIndex = 17
objExcel.Selection.Font.ColorIndex = 1
objExcel.Selection.Font.Bold = True
objExcel.Cells.EntireColumn.AutoFit

'start count at row 2
x = 2

'Set objOutputFile = objFSO.OpenTextFile(strScriptPath & "\" & "Check_Existance_HPSA_results.csv", 2, True)
'objOutputFile.WriteLine "Server Name" & "," & "HPSA OpswareAgent ""WatchDog.exe"" file exist?" & _
'	"," & "OpswareAgent Service Status" & "," & "Errors"

strDomain = InputBox("Please enter your Domain name: ")
strUsername = InputBox("Please enter your Username: ")
strPassword = InputBox("Please enter your Password: ")

'Echo Script Start time
dtSDate = Date
dtStart = Time
WScript.Echo "Please be patient. Script is processing your request...." & vbCrLf & vbCrLf
WScript.Echo "Script Start Time: " & dtSDate & " " & dtStart

'Count total records from File
'This will display "Processing Record: xx of xxx
Set objRecCount = CreateObject("Scripting.FileSystemObject")
Set fileContent = objRecCount.OpenTextFile(strFullPath, 1)
totalLineCount = UBound(Split(fileContent.ReadAll, vbLf)) + 1
fileContent.Close
Set fileContent = Nothing
Set objRecCount = Nothing

'Pass In Server name, Ping It, Call CheckHpsaStatus
Do Until objInputFile.AtEndOfLine
	strServer = ""
	strServer = UCase(objInputFile.ReadLine)
	
	Set objShell = CreateObject("WScript.Shell")
	Set objExec = objShell.Exec("Ping -n 2 -w 500 " & strServer)
	strPingResults = LCase(objExec.StdOut.ReadAll)

	Set objNetwork = CreateObject("WScript.Network")
	objNetwork.MapNetworkDrive "R:", "\\" & strServer & "\" & "c$", False, strUsername, strPassword
	'check for network connection error's
	'prior to checking for Hpsa file & status
	If Err = 0 Then
		'Perform ping and check for hpsa
		If InStr(strPingResults, "reply from") Then
			iRow = x
			
			Call CheckHpsaStatus(iRow, strServer)
			
			If Err.Number <> 0 Then
				strError = Err.Description
				WriteToExcel iRow, strServer, "N/A", "N/A", "Error Description: " & strError & "." & _
													" Error number: " & Err.Number & "."
				Err.Clear()
			End If
		Else
			'ping fails
			iRow = x
			WriteToExcel iRow, strServer, "N/A", "N/A", "Ping failed."
		End If
	Else
		'unable to connect to remote server's Unc path
		iRow = x
		strErrDescrip = Trim(Err.Description)
		WriteToExcel iRow, strServer, "N/A", "N/A", "Error Number: " & Err.Number & _
			"; " & "Error Description: " & strErrDescrip
		Err.Clear()
	End If
	
	x = x + 1
	
	'Output current process status
	'to DOS Cmd shell
	iCounter = iCounter + 1
	WScript.Echo "Processing record " & iCounter & " of " & totalLineCount
	strPrcntgComp = (iCounter / totalLineCount) * 100
	strPrcntgComp = Left(strPrcntgComp, 5)
	WScript.Echo "Percent Complete: " & strPrcntgComp & "%"
	WScript.Echo
	
	objNetwork.RemoveNetworkDrive "R:", True, True
	
	Set objShell = Nothing
	Set objExec = Nothing
	Set objNetwork = Nothing
Loop

strQDate = Date
arrQDate = Split(strQDate, "/")
strQDate = arrQDate(0) & "-" & arrQDate(1) & "-" & arrQDate(2)
strQTime = Time
arrQTime = Split(strQTime, ":")
strQTime = arrQTime(0) & "-" & arrQTime(1) & "-" & arrQTime(2)

objExcel.ActiveWorkbook.SaveAs strScriptPath & "\" & _
	"Check_Existance_HPSA_results_" & strQDate & "_" & strQTime & "_" & ".xlsx" 
objExcel.Quit

'Verify existance of HPSA OpswareAgent
'Service file and Service Status
Sub CheckHpsaStatus(iRow, server)
		Set objLocator = CreateObject("WbemScripting.SWbemLocator")
		Set objWMIService = objLocator.ConnectServer(server, "\root\cimv2", strDomain & "\" & strUsername, strPassword)
		objWMIService.Security_.ImpersonationLevel = WbemImpersonationLevelImpersonate
		objWMIService.Security_.AuthenticationLevel = WbemAuthenticationLevelPktPrivacy

		If Err Then
			Exit Sub
		End If
		
		'Determine if OpswareAgent Service file exist
		If objFSO.FileExists(strTrgtFile) = True Then
			Set colServices = objWMIService.ExecQuery _
			("SELECT StartMode, State FROM Win32_Service WHERE Name LIKE'" & strService & "'")
			'Check status of OpswareAgent Service
			For Each objService In colServices
				If Not IsNull(objService) Then
					WriteToExcel iRow, server, "Yes", """" & objService.Name & """" & _
									" is currently " & objService.State & " and " & _
										objService.StartMode & ".", "N/A"
				Else
					WriteToExcel iRow, server, "N/A", "Service " & """" & strService & """" & _
												" was not found.", "N/A" 
				End If
			Next
		Else
			WriteToExcel iRow, server, "No", "N/A", "N/A" 
		End If
		
		Set objLocator = Nothing
		Set objWMIService = Nothing
		Set colServices = Nothing
		server = ""
End Sub

Sub WriteToExcel(iRow, srv, hpsa, service, errors)
	objExcel.Cells(iRow, 1).Value = srv
	objExcel.Cells(iRow, 2).Value = hpsa
	objExcel.Cells(iRow, 3).Value = service
	objExcel.Cells(iRow, 4).Value = errors
End Sub

'Function to Convert the span time of "seconds
'to HH:MM:SS
Function TimeSpan(dt1, dt2)
	Dim strLenDt1, strLenDt2
	Dim seconds, minutes, hours 
	strLenDt1 = Len(dt1)
	strLenDt2 = Len(dt2)
	dt1 = Trim(Left(dt1, strLenDt1 - 3))
	dt2 = Trim(Left(dt2, strLenDt2 - 3))
	If IsDate(dt1) And IsDate(dt2) = False Then
		TimeSpan = "00:00:00"
		Exit Function
	End If
		seconds = Abs(DateDiff("s", dt1, dt2))
		minutes = seconds \ 60
		hours = minutes \ 60
		seconds = seconds Mod 60
		minutes = minutes Mod 60
		
		'If Len(hours) = 1 Then hours = 0 & hours
		
		TimeSpan = hours & " Hour(s), " & _
			Right("00" & minutes, 2) & " Minute(s), " & _
			Right("00" & seconds, 2) & " Second(s)"
End Function

'Echo Script Finish time, Total Processing time 
'and Total Records proccessed upon script completion
dtFDate = Date
dtFTime = Time
WScript.Echo
WScript.Echo "Script Finish Time: " & dtFDate & " " & dtFTime & vbCrLf
WScript.Echo "Total Processing Time: " & TimeSpan(dtStart, dtFTime)
WScript.Echo "Total Records processed: " & iCounter & " of " & totalLineCount
WScript.Echo "Percent Completed: " & strPrcntgComp & "%"

WScript.Echo "" & vbCrLf
WScript.Echo "######################################################################" & vbCrLf & _
			 "#                                                                    #" & vbCrLf & _
			 "# PROCESSING OF THE Check_Existance_HPSA.vbs HAS COMPLETED!!         #" & vbCrLf & _
			 "#                                                                    #" & vbCrLf & _
			 "# Output file: Check_Existance_HPSA_results.xlsx                      #" & vbCrLf & _
			 "#                                                                    #" & vbCrLf & _
			 "######################################################################"
WScript.Quit

Open in new window

RobSampsonCommented:
OK cool.  Just one thing, you should check if R drive exists before removing it, just to prevent an error that might occur.

      If objFSO.DriveExists("R:") = True Then objNetwork.RemoveNetworkDrive "R:", True, True

Regards,

Rob.
wally_davisAuthor Commented:
Hey Rob, Good point. I'll update my code.
Also, I'm getting some mixed results on output. I've combed through my code and for some Servers that look like you can't get a connection to, when I spot check and run RDC, I'm able to connect to some of these Servers. Can you look through my code and see if I'm properly destroying objects and if its possible that I may need to put the Code to Sleep during Remote drive mappings? Thank you!
RobSampsonCommented:
I never did attach my cmdkey.....it is now attached....rename it to exe.

It looks like you're mapping the drive outside of the ping, which is not a good sequence.  You're better off pinging first, then mapping the drive.  Also, WMI connection is different to RDP connection, so there may be some incorrect permissions on WMI (usually DCOM security) or WMI is not working correctly.

Swap around the pinging with the drive mapping, and see if that makes a difference.  The objects and variables are all getting new, current, values before being tested, so that shouldn't be a problem.

Regards,

Rob.
cmdkey.txt
wally_davisAuthor Commented:
Rob, I've noticed that the Servers I seem to be having issues with seem to be Windows 2000 Servers.
So, I decided to run a UNC Connection to this server, i.e. \\ServerName\c$ and I received the following message:
"Logon failure. User Account restriction. Possible reasons are blank passwords are not allowed, logon hour restrictions, or a policy restriction has been enforced."
I made a few changes in the local "User Rights Assignment" and "Security Options" policies and still didn't help. I added my normal logon ID and Super User ID to the local administrators group and then I got a different error message when connecting via UNC and it was "Network path was not found". But, I'm RDC'd into the Server. So there is some setting that is preventing my script from mapping a drive. What a pain! Any ideas on anything else I might be able to try?
'Created 4/21/2010 - Wallace Davis
'Verify existance of HPSA OpswareAgent
'Service file and Service Status

Option Explicit

On Error Resume Next

Const WbemImpersonationLevelImpersonate = 3
Const WbemAuthenticationLevelPktPrivacy = 6

Dim x, iRow, iCounter, fileContent, totalLineCount
Dim dtSDate, dtStart, dtFinish, dtFDate, dtFTime
Dim strService, strTrgtFile, strServer, strServers, server
Dim strScriptPath, strFullPath, strPingResults, strPrcntgComp
Dim strDomain, strUsername, strPassword, strTestFile, strTestPath
Dim strCommand, strCommand2, strQDate, strQTime, arrQDate, arrQTime
Dim objExcel, objFSO, objInputFile, objOutputFile, objLocator, objNetwork
Dim objRecCount, objWMIService, objShell, objExec, objService
Dim colServices

Const xlCenter = -4108

'Service and Service file to be verified
strService = "OpswareAgent"
strTrgtFile = "R:\Progra~1\Opsware\agent\pylibs\watchdog\watchdog.exe"

Set objFSO = CreateObject("Scripting.FileSystemObject")

strScriptPath = objFSO.GetParentFolderName(WScript.ScriptFullName)

If (WScript.Arguments.Count > 0) Then
	strServers = WScript.Arguments.Item(0)
	strFullPath = strScriptPath & "\" & strServers
	
	If objFSO.FileExists(strFullPath) Then
		strServer = LCase(strServers)
		Set objInputFile = objFSO.OpenTextFile(strServer, 1)
	Else
		WScript.Echo "#############################################################################"
		WScript.Echo "#                                                                           #"
		WScript.Echo "#    Error: Unable to open file " & strServers & " for output.                  #"
		WScript.Echo "#                                                                           #"
		WScript.Echo "#    Important: Verify your script & filename spelling and                  #"
		WScript.Echo "#               that its in the same path as your script.                   #"
		WScript.Echo "#                                                                           #"				
		WScript.Echo "#############################################################################"
		WScript.Quit
	End If
Else
	WScript.Echo "#############################################################################"
	WScript.Echo "#                                                                           #"
	WScript.Echo "#    Usage: Check_Existance_HPSA.vbs serverlist.txt                         #"
	WScript.Echo "#                                                                           #"		
	WScript.Echo "#    Important: Verify your script & filename spelling and                  #"
	WScript.Echo "#               that its in the same path as your script.                   #"	
	WScript.Echo "#                                                                           #"				
	WScript.Echo "#############################################################################"
	WScript.Quit
End If

'Create Excel object and worksheet
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.Workbooks.Add

'Excel header columns, first row
objExcel.Cells(1, 1).Value = "Server Name"
objExcel.Cells(1, 2).Value = "HPSA OpswareAgent ""Watchdog.exe"" file exist?"
objExcel.Cells(1, 3).Value = "OpswareAgent Service Status" 
objExcel.Cells(1, 4).Value = "Errors"

'Excel range and formatting
objExcel.Range("A1:D1").Select
objExcel.Selection.Interior.ColorIndex = 17
objExcel.Selection.Font.ColorIndex = 1
objExcel.Selection.Font.Bold = True
objExcel.Cells.EntireColumn.AutoFit

'start count at row 2
x = 2

'Set objOutputFile = objFSO.OpenTextFile(strScriptPath & "\" & "Check_Existance_HPSA_results.csv", 2, True)
'objOutputFile.WriteLine "Server Name" & "," & "HPSA OpswareAgent ""WatchDog.exe"" file exist?" & _
'	"," & "OpswareAgent Service Status" & "," & "Errors"

strDomain = InputBox("Please enter your Domain name: ")
strUsername = InputBox("Please enter your Username: ")
strPassword = InputBox("Please enter your Password: ")

'Echo Script Start time
dtSDate = Date
dtStart = Time
WScript.Echo "Please be patient. Script is processing your request...." & vbCrLf & vbCrLf
WScript.Echo "Script Start Time: " & dtSDate & " " & dtStart

'Count total records from File
'This will display "Processing Record: xx of xxx
Set objRecCount = CreateObject("Scripting.FileSystemObject")
Set fileContent = objRecCount.OpenTextFile(strFullPath, 1)
totalLineCount = UBound(Split(fileContent.ReadAll, vbLf)) + 1
fileContent.Close
Set fileContent = Nothing
Set objRecCount = Nothing

'Pass In Server name, Ping It, Call CheckHpsaStatus
Do Until objInputFile.AtEndOfLine
	strServer = ""
	strServer = UCase(objInputFile.ReadLine)
	
	Set objShell = CreateObject("WScript.Shell")
	Set objExec = objShell.Exec("Ping -n 2 -w 500 " & strServer)
	strPingResults = LCase(objExec.StdOut.ReadAll)

	'Perform ping and check for hpsa
	If InStr(strPingResults, "reply from") Then
		'check for network connection error's
		'prior to checking for Hpsa file & status
		Set objNetwork = CreateObject("WScript.Network")
		If objFSO.DriveExists("R:") = True Then objNetwork.RemoveNetworkDrive "R:", True, True
		WScript.Sleep 500
		objNetwork.MapNetworkDrive "R:", "\\" & strServer & "\" & "c$", False, strUsername, strPassword
		WScript.Sleep 2000
		
		If Err = 0 Then
			iRow = x
		
			Call CheckHpsaStatus(iRow, strServer)
			
			If Err.Number <> 0 Then
				WriteToExcel iRow, strServer, "N/A", "N/A", "Error Description: " & Err.Description & "." & _
													" Error number: " & Err.Number & "."
				Err.Clear()
			End If
		Else
			'unable to connect to remote server's Unc path
			iRow = x
			WriteToExcel iRow, strServer, "N/A", "N/A", "Error Number: " & Err.Number & _
				"; " & "Error Description: " & Err.Description
			Err.Clear()
		End If
		
	Else
		'ping fails
		iRow = x
		WriteToExcel iRow, strServer, "N/A", "N/A", "Ping failed."
		Err.Clear
	End If
	
	x = x + 1
	
	'Output current process status
	'to DOS Cmd shell
	iCounter = iCounter + 1
	WScript.Echo "Processing record " & iCounter & " of " & totalLineCount
	strPrcntgComp = (iCounter / totalLineCount) * 100
	strPrcntgComp = Left(strPrcntgComp, 5)
	WScript.Echo "Percent Complete: " & strPrcntgComp & "%"
	WScript.Echo
	
	If objFSO.DriveExists("R:") = True Then objNetwork.RemoveNetworkDrive "R:", True, True
	WScript.Sleep 500
	
	Set objShell = Nothing
	Set objExec = Nothing
	Set objNetwork = Nothing
Loop

strQDate = Date
arrQDate = Split(strQDate, "/")
strQDate = arrQDate(0) & "-" & arrQDate(1) & "-" & arrQDate(2)
strQTime = Time
arrQTime = Split(strQTime, ":")
strQTime = arrQTime(0) & "." & arrQTime(1) & "." & arrQTime(2)

Dim strXlFinal : strXlFinal = strScriptPath & "\" & _
	"Check_Existance_HPSA_results_" & strQDate & "_" & strQTime & "_" & ".xlsx"
objExcel.ActiveWorkbook.SaveAs strXlFinal
objExcel.Workbooks(strXlFinal).Sheets("Sheet1").Range("A:D").Entirecolumn.Autofit
objExcel.Quit

'Verify existance of HPSA OpswareAgent
'Service file and Service Status
Sub CheckHpsaStatus(iRow, server)
		Set objLocator = CreateObject("WbemScripting.SWbemLocator")
		Set objWMIService = objLocator.ConnectServer(server, "\root\cimv2", strDomain & "\" & strUsername, strPassword)
		objWMIService.Security_.ImpersonationLevel = WbemImpersonationLevelImpersonate
		objWMIService.Security_.AuthenticationLevel = WbemAuthenticationLevelPktPrivacy

		If Err Then
			Exit Sub
		End If
		
		'Determine if OpswareAgent Service file exist
		If objFSO.FileExists(strTrgtFile) = True Then
			Set colServices = objWMIService.ExecQuery _
			("SELECT StartMode, State FROM Win32_Service WHERE Name LIKE'" & strService & "'")
			'Check status of OpswareAgent Service
			For Each objService In colServices
				If Not IsNull(objService) Then
					WriteToExcel iRow, server, "Yes", """" & objService.Name & """" & _
									" is currently " & objService.State & " and " & _
										objService.StartMode & ".", "N/A"
				Else
					WriteToExcel iRow, server, "N/A", "Service " & """" & strService & """" & _
												" was not found.", "N/A" 
				End If
			Next
		Else
			WriteToExcel iRow, server, "No", "N/A", "N/A" 
		End If
		
		Set objLocator = Nothing
		Set objWMIService = Nothing
		Set colServices = Nothing
		server = ""
End Sub

Sub WriteToExcel(iRow, srv, hpsa, service, errors)
	objExcel.Cells(iRow, 1).Value = srv
	objExcel.Cells(iRow, 2).Value = hpsa
	objExcel.Cells(iRow, 3).Value = service
	objExcel.Cells(iRow, 4).Value = errors
	objExcel.Cells.VerticalAlignment = xlCenter
	objExcel.Cells.HorizontalAlignment = xlCenter
End Sub

'Function to Convert the span time of "seconds
'to HH:MM:SS
Function TimeSpan(dt1, dt2)
	Dim strLenDt1, strLenDt2
	Dim seconds, minutes, hours 
	strLenDt1 = Len(dt1)
	strLenDt2 = Len(dt2)
	dt1 = Trim(Left(dt1, strLenDt1 - 3))
	dt2 = Trim(Left(dt2, strLenDt2 - 3))
	If IsDate(dt1) And IsDate(dt2) = False Then
		TimeSpan = "00:00:00"
		Exit Function
	End If
		seconds = Abs(DateDiff("s", dt1, dt2))
		minutes = seconds \ 60
		hours = minutes \ 60
		seconds = seconds Mod 60
		minutes = minutes Mod 60
		
		'If Len(hours) = 1 Then hours = 0 & hours
		
		TimeSpan = hours & " Hour(s), " & _
			Right("00" & minutes, 2) & " Minute(s), " & _
			Right("00" & seconds, 2) & " Second(s)"
End Function

'Echo Script Finish time, Total Processing time 
'and Total Records proccessed upon script completion
dtFDate = Date
dtFTime = Time
WScript.Echo
WScript.Echo "Script Finish Time: " & dtFDate & " " & dtFTime & vbCrLf
WScript.Echo "Total Processing Time: " & TimeSpan(dtStart, dtFTime)
WScript.Echo "Total Records processed: " & iCounter & " of " & totalLineCount
WScript.Echo "Percent Completed: " & strPrcntgComp & "%"

WScript.Echo "" & vbCrLf
WScript.Echo "######################################################################" & vbCrLf & _
			 "#                                                                    #" & vbCrLf & _
			 "# PROCESSING OF THE Check_Existance_HPSA.vbs HAS COMPLETED!!         #" & vbCrLf & _
			 "#                                                                    #" & vbCrLf & _
			 "# Output file: Check_Existance_HPSA_results.xlsx                      #" & vbCrLf & _
			 "#                                                                    #" & vbCrLf & _
			 "######################################################################"
WScript.Quit

Open in new window

RobSampsonCommented:
Hi Wally,

You will need to be using credentials that are a member of the local Administrators group on those servers.  You should also verify that the C$ share is available on those machines.  I know that Windows XP recreates the C$ share if it is removed, but I can't remember if Windows 2K did.  Maybe someone removed them as a security measure?

Right click My Computer, and click Manage. expand Shared Folders and click Shares.  Verify the C$ share exists.  If not, right-click the C drive in My Computer, and add it.

Regards,

Rob.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
VB Script

From novice to tech pro — start learning today.