Strange VBScript error: Object required: 'objFolder' - vbscript

I have done extensive search on internet but still was not able to find the solution. The interesting thing is that my code worked before. I am using html page with VBScript code, opened using IE 9.
My code is below:
29: Function TraverseDirectory(objFolder, searchTerm, outFile)
30: if objFolder.SubFolders.Count > 0 then <-- ERROR shown in this line: Object required: 'objFolder'
31: MsgBox objFolder.SubFolders.Count <-- This message is shown without an issue
32: Set fc = objFolder.SubFolders
33: For Each f1 in fc
34: ProcessFolder f1, searchTerm, outFile
35: TraverseDirectory f1, searchTerm, outFile
36: Next
37: else
38: ProcessFolder objFolder, searchTerm, outFile
39: end if
40: End Function
I am showing the error in line 30: Object required 'objFolder'
I added a message box in line 31 and it was reached, outputting message box with a number of subfolders in a give folder. If the problem was actually in line 30, it would never reach line 31. If I completely remove line 31 (the one with a message box), I still get the same error in line 30.
My function above is called the following way:
Set objFolder = objFSO.GetFolder("C:\Test")
TraverseDirectory objFolder, str, outFile
The folder exists and is retrieved without a problem. Not sure what is happening. Can someone shed some light on the issue?

Next script collects/echoes some debugging info as advised in my previous comment
option explicit
'On Error Resume Next
On Error GoTo 0
Dim strResult: strResult = Wscript.ScriptName
Dim objfso, str, outfile, objFolder
set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("D:\TestC")
'Set objFolder = objFSO.GetFolder("C:\attachments") 'an empty folder for debugging'
Wscript.Echo "start" & vbTab _
& VarType( objFolder) & " " & TypeName(objFolder) & vbTab & objFolder
TraverseDirectory objFolder, str, outFile
Wscript.Echo strResult
Wscript.Quit
Function TraverseDirectory(objFolder, searchTerm, outFile)
Dim fc, f1, aux
Wscript.Echo "debug" & vbTab _
& VarType( objFolder) & " " & TypeName(objFolder) & vbTab & objFolder
aux = objFolder.SubFolders.Count
if aux > 0 then '<-- ERROR shown in this line: Object required: 'objFolder'
'MsgBox objFolder.SubFolders.Count ' <-- This message is shown without an issue
Set fc = objFolder.SubFolders
For Each f1 in fc
strResult = strResult & vbNewLine & Cstr( aux) _
& vbTab & VarType( f1) & " " & TypeName(f1) & vbTab & f1
'ProcessFolder f1, searchTerm, outFile
TraverseDirectory f1, searchTerm, outFile
Next
else
'ProcessFolder objFolder, searchTerm, outFile
strResult = strResult & vbNewLine & Cstr( aux) & vbTab _
& VarType( objFolder) & " " & TypeName(objFolder) & vbTab & objFolder
end if
End Function
Debugging scenario:
==> tree "D:\TestC"
Folder PATH listing for volume DataDisk
Volume serial number is … … …
D:\TESTC
├───bubu
│ └───foobar
├───kuku
├───New Folder 12
└───New Folder 21
└───New folder XX
Output shows that leafs in folder tree are processed twice so the script above requires more thinking and debugging: note that strResult variable is updated in place of original ProcessFolder call:
==> cscript D:\VB_scripts\SO\38056552.vbs
start 8 Folder D:\testC
debug 8 Folder D:\testC
debug 8 Folder D:\testC\bubu
debug 8 Folder D:\testC\bubu\foobar
debug 8 Folder D:\testC\kuku
debug 8 Folder D:\testC\New Folder 12
debug 8 Folder D:\testC\New Folder 21
debug 8 Folder D:\testC\New Folder 21\New folder XX
38056552.vbs
4 8 Folder D:\testC\bubu
1 8 Folder D:\testC\bubu\foobar
0 8 Folder D:\testC\bubu\foobar
4 8 Folder D:\testC\kuku
0 8 Folder D:\testC\kuku
4 8 Folder D:\testC\New Folder 12
0 8 Folder D:\testC\New Folder 12
4 8 Folder D:\testC\New Folder 21
1 8 Folder D:\testC\New Folder 21\New folder XX
0 8 Folder D:\testC\New Folder 21\New folder XX

Related

VBS/BAT - Show Progress of Script Execution

I have roughly 8 scripts that need to be executed, and some of the scripts may sometimes take a while to complete the execution and all you get to see is the message box at the end of the script that says completed once everything is done..
I am looking for a way to show some form of progress/progress bar while the scripts execute, if this is even possible?
I read somewhere that it is easier/possible to show a progress bar in command line, but all my code are in vbscript files..
Currently, I have a bat file that calls and executes my scripts for me.
Here is an example of just one of my scripts that takes a while - This code looks in a specific path directory for the 3 latest csv files and then copies them to a new location:
Option Explicit
Dim FolderToCheck, FolderDestination, FileExt, mostRecent, noFiles, fso, fileList, file, filecounter, oShell, strHomeFolder
' Enumerate current user's home path - we will use that by default later if nothing specified in commandline
Set oShell = CreateObject("WScript.Shell")
'Variables -----
folderToCheck = strHomeFolder & "X:\Data\Terminations\Daily_Terminations" ' Folder Source to check for recent files to copy FROM
folderDestination = strHomeFolder & "X:\Test\Terminations" ' Destination Folder where to copy files TO
fileExt = "csv" ' Extension we are searching for
mostRecent = 3 ' Most Recent number of files to copy
' --------------
PreProcessing() ' Retrieve Command Line Parameters
' Display what we are intending on doing
'wscript.echo "Checking Source: " & FolderToCheck & "For Files of type: " & FileExt
'wscript.echo "Copying most recent file(s) to: " & FolderDestination & "."
noFiles = TRUE
Set fso = CreateObject("Scripting.FileSystemObject")
Set fileList = CreateObject("ADOR.Recordset")
fileList.Fields.append "name", 200, 255
fileList.Fields.Append "date", 7
fileList.Open
If fso.FolderExists(FolderToCheck) Then
For Each file In fso.GetFolder(FolderToCheck).files
If LCase(fso.GetExtensionName(file)) = LCase(FileExt) then
fileList.AddNew
fileList("name").Value = File.Path
fileList("date").Value = File.DateLastModified
fileList.Update
If noFiles Then noFiles = FALSE
End If
Next
If Not(noFiles) Then
'wscript.echo fileList.recordCount & " File(s) found. Sorting and copying last " & mostRecent &"..."
fileList.Sort = "date DESC"
If Not(fileList.EOF) Then
fileList.MoveFirst
If fileList.recordCount < mostRecent Then
wscript.echo "WARNING: " & mostRecent &" file(s) specified but only " & fileList.recordcount & " file(s) match criteria. Adjusted to " & fileList.RecordCount & "."
mostRecent = fileList.recordcount
End If
fileCounter = 0
Do Until fileList.EOF Or fileCounter => mostRecent
If Not(fso.FolderExists(folderDestination)) Then
wscript.echo "Destination Folder did not exist. Creating..."
fso.createFolder folderDestination
End If
fso.copyfile fileList("name"), folderDestination & "\", True
'wscript.echo fileList("date").value & vbTab & fileList("name")
fileList.moveNext
fileCounter = fileCounter + 1
Loop
wscript.echo "Files Seccuessfully Copied"
Else
wscript.echo "An unexpected error has occured."
End If
Else
wscript.echo "No matching """ & FileExt &""" files were found in """ & foldertocheck & """ to copy."
End If
Else
wscript.echo "Error: Source folder does not exist """ & foldertocheck & """."
End If
fileList.Close
Function PreProcessing
Dim source, destination, ext, recent
' Initialize some variables
Set source = Nothing
Set destination = Nothing
Set ext = Nothing
Set recent = Nothing
source = wscript.arguments.Named.Item("source")
destination = wscript.arguments.Named.Item("destination")
ext = wscript.arguments.Named.Item("ext")
recent = wscript.arguments.Named.Item("recent")
If source <> "" Then FolderToCheck = source
If destination <> "" Then FolderDestination = destination
If ext <> "" Then FileExt = ext
If recent <> "" Then mostRecent = int(recent)
End Function

Uploading folder content to FTP with VBScript gives dialog box to overwrite existing file

This is one of the first times I am using VBScript to create a task I want to run in a program called Qlikview.
What I want to do is upload all the content of one local folder to an FTP folder but when a file is already on that FTP folder it just needs to "Overwrite All" so do "Yes to All" automatically
Here is my code:
Function FTPUpload(FTPHost, FTPUser, FTPPass, FTPPath)
Set oShell = CreateObject("Shell.Application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
'Copy Options: 16 = Yes to All
Const copyType = 16
strFTP = "ftp://" & FTPUser & ":" & FTPPass & "#" & FTPHost
Set objFTP = oShell.NameSpace(strFTP)
'Upload all files in folder
If objFSO.FolderExists(FTPPath) Then
'Code below can be used to upload entire folder
Set objFolder = oShell.NameSpace(FTPPath)
Wscript.Echo "Uploading folder " & FTPPath & " to " & strFTP
objFTP.CopyHere objFolder.Items, copyType
End If
'If Err.Number <> 0 Then
' Wscript.Echo "Error: " & Err.Description
'End If
On Error Goto 0
End function
I use objFTP.CopyHere objFolder.Items, copyType to copy the content and copyType = 16 I found this on the internet Here where 16 stands for "Yes to All" when a dialog appears.
The problem is when I run this code, it uploads to the FTP but when a file exists I keep getting the overwrite dialog. What could be the problem?

VBScript Error code 800A0409, Unterminated string constant, on line 1

I'm getting Error code 800A0409, Unterminated string constant, on line 1, 54 with the code below.
Option Explicit
Dim ObjProgressMsg
Dim fso,objText,strVstup,strVystup,f,dtmVyt,dtmF,dDiff,fName,fExt,fShort,dtmAkt,tx,msgText
Dim strMessage,strWindowTitle,strTemp,wshShell,objTempMessage,strTempVBS
Set fso = CreateObject("Scripting.FileSystemObject")
Set objText = fso.GetFile("l:\bat\posledni.den")
strVstup = "l:\filefolder\"
strVystup = "l:\backup"
dtmVyt = objText.DateLastModified
msgText = "Some text about copying and renaming" & VbCrLf & "files, please wait..."
ProgressMsg msgText
For Each f In fso.GetFolder(strVstup).Files
dtmF = f.DateLastModified
dDiff = DateDiff("s", dtmF, dtmVyt)
If dDiff < 0 Then
ProgressMsg ""
WScript.Echo f
End If
Next
WScript.Echo "Some text about the task being finished."
Function ProgressMsg( strMessage )
' Written by Denis St-Pierre
' Displays a progress message box that the originating script can kill in both 2k and XP
' If StrMessage is blank, take down previous progress message box
' Using 4096 in Msgbox below makes the progress message float on top of things
' CAVEAT: You must have Dim ObjProgressMsg at the top of your script for this to work as described
Set wshShell = WScript.CreateObject( "WScript.Shell" )
strTEMP = wshShell.ExpandEnvironmentStrings( "%TEMP%" )
If strMessage = "" Then
' Disable Error Checking in case objProgressMsg doesn't exists yet
On Error Resume Next
' Kill ProgressMsg
objProgressMsg.Terminate( )
' Re-enable Error Checking
On Error Goto 0
Exit Function
End If
strTempVBS = strTEMP + "\" & "Message.vbs" 'Control File for reboot
' Create Message.vbs, True=overwrite
Set objTempMessage = fso.CreateTextFile( strTempVBS, True )
objTempMessage.WriteLine( "MsgBox""" & strMessage & """, 4096, """ & "a_sp_rano" & """" )
objTempMessage.Close
' Disable Error Checking in case objProgressMsg doesn't exists yet
On Error Resume Next
' Kills the Previous ProgressMsg
objProgressMsg.Terminate( )
' Re-enable Error Checking
On Error Goto 0
' Trigger objProgressMsg and keep an object on it
Set objProgressMsg = WshShell.Exec( "%windir%\system32\wscript.exe " & strTempVBS )
End Function
The script should show a msgbox while searching for files newer than last modified date of posledni.den file. Then once it finds a file it should close msgbox and echo the file it found.
It works just fine if I change this:
msgText = "Some text about copying and renaming" & VbCrLf & "files, please wait..."
to this:
msgText = "Some text about copying and renaming" & "files, please wait..."
Removal of VbCrLf seems to fix that error, just no line break is obviously happening. I can't figure out why it's behaving like that, what am I doing wrong. Every kind of insight on the problem would be much appreciated.
Thank you in advance. :)
The error occurs in the execution of the generated .vbs. What you do is:
>> msg1 = "A" & vbCrLf & "B"
>> code = "MsgBox """ & msg1 & """"
>> WScript.Echo code
>>
MsgBox "A
B"
>> Execute code
>>
Error Number: 1033
Error Description: Unterminated string constant
What you should do:
>> msg1 = """A"" & vbCrLf & ""B"""
>> WScript.Echo msg1
>>
"A" & vbCrLf & "B"
>> code = "MsgBox " & msg1 & ", 4096"
>> WScript.Echo code
>>
MsgBox "A" & vbCrLf & "B", 4096
>> Execute code
>>
>> <-- no news are good news; message displayed

Copy 1 latest extension MDB file from a source folder to destination folder for WIN 2000

I have a script whereby this will copy 2 files(ext: txt) from a source folder to destination folder based on the latest date file. I have tested with WIN 7 and Vista and it is working fine. I get the output that i wanted. When i tested with WIN 2000 with different file extension MDB file and folder path, i could not get the output. Here, i have edit to only copy 1 latest file. Please check the script below and help me :-(
Option Explicit
Dim FolderToCheck, FolderDestination, FileExt, mostRecent, noFiles, fso, fileList, file, filecounter, oShell, strHomeFolder
' Enumerate current user's home path - we will use that by default later if nothing specified in commandline
Set oShell = CreateObject("WScript.Shell")
strHomeFolder = oShell.ExpandEnvironmentStrings("%USERPROFILE%")
'Variables -----
folderToCheck = strHomeFolder & "C:\Mms2\MDB"' Folder Source to check for recent files to copy FROM
folderDestination = strHomeFolder & "C:\Documents and Settings\Mms\Desktop\Test"'Destination Folder where to copy files TO
fileExt = "MDB" ' Extension we are searching for
mostRecent = 1 ' Most Recent number of files to copy
' --------------
'PreProcessing() ' Retrieve Command Line Parameters
' Display what we are intending on doing
' wscript.echo "Checking Source: " & FolderToCheck
' wscript.echo "For Files of type: " & FileExt
' wscript.echo "Copying most recent "& mostRecent &" file(s) to: " & FolderDestination & "."
' wscript.echo
noFiles = TRUE
Set fso = CreateObject("Scripting.FileSystemObject")
Set fileList = CreateObject("ADOR.Recordset")
fileList.Fields.append "name", 200, 255
fileList.Fields.Append "date", 7
fileList.Open
If fso.FolderExists(FolderToCheck) Then
For Each file In fso.GetFolder(FolderToCheck).files
If LCase(fso.GetExtensionName(file)) = LCase(FileExt) then
fileList.AddNew
fileList("name").Value = File.Path
fileList("date").Value = File.DateLastModified
fileList.Update
If noFiles Then noFiles = FALSE
End If
Next
If Not(noFiles) Then
' wscript.echo fileList.recordCount & " File(s) found. Sorting and copying last " & mostRecent &"..."
fileList.Sort = "date DESC"
If Not(fileList.EOF) Then
fileList.MoveFirst
If fileList.recordCount < mostRecent Then
' wscript.echo "WARNING: " & mostRecent &" file(s) specified but only " & fileList.recordcount & " file(s) match criteria. Adjusted to " & fileList.RecordCount & "."
mostRecent = fileList.recordcount
End If
fileCounter = 0
Do Until fileList.EOF Or fileCounter => mostRecent
If Not(fso.FolderExists(folderDestination)) Then
' wscript.echo "Destination Folder did not exist. Creating..."
fso.createFolder folderDestination
End If
fso.copyfile fileList("name"), folderDestination & "\", True
' wscript.echo fileList("date").value & vbTab & fileList("name")
fileList.moveNext
fileCounter = fileCounter + 1
Loop
Else
' wscript.echo "An unexpected error has occured."
End If
Else
' wscript.echo "No matching """ & FileExt &""" files were found in """ & foldertocheck & """ to copy."
End If
Else
' wscript.echo "Error: Source folder does not exist """ & foldertocheck & """."
End If
fileList.Close
Function PreProcessing
Dim source, destination, ext, recent
' Initialize some variables
Set source = Nothing
Set destination = Nothing
Set ext = Nothing
Set recent = Nothing
'Get Command Line arguments
' <scriptname>.vbs /Source:"C:\somepath\somefolder" /Destination:"C:\someotherpath\somefolder" /ext:MDB /recent:1
source = wscript.arguments.Named.Item("source")
destination = wscript.arguments.Named.Item("destination")
ext = wscript.arguments.Named.Item("ext")
recent = wscript.arguments.Named.Item("recent")
If source <> "" Then FolderToCheck = source
If destination <> "" Then FolderDestination = destination
If ext <> "" Then FileExt = ext
If recent <> "" Then mostRecent = int(recent)
End Function
you'll need to change a few things:
Remove these lines - they're not required any more:
' Enumerate current user's home path - we will use that by default later if nothing specified in commandline
Set oShell = CreateObject("WScript.Shell")
strHomeFolder = oShell.ExpandEnvironmentStrings("%USERPROFILE%")
Update these lines:
'Variables -----
folderToCheck = "C:\Mms2\MDB" ' Folder Source to check for recent files to copy FROM
folderDestination = "C:\Documents and Settings\Mms\Desktop\Test" 'Destination Folder where to copy files TO

Can't stop a service using vbscript

I'm using the following code to try to stop a service. I can display the service state using WScript.Echo objService.State so I know I have the right service name and that it can find it and determine its state as running or stopped but when I run this script I get an Error on Line 51: Error Not Found Code 80041002 (see screenshot)
The line of code at 51 is:
objService.StopService()
Where am I going wrong? I can stop and start this via the command line using sc.exe and am able to control other services ie Alerter but as soon as I try to control this particular service it fails.
Thanks
EDIT The full code from the script (Thanks Brandon Moretz who pointed out
that I hadn't posted the full code so
the Line number didn't mean anything &
I have changed the StartService() back
to Stop as it originally was so now you have more to go on. Sorry!)
' 1. Check that the latest backup zip exists and store its name in LBZ (LatestBackupZip)
' 2. Stop the Livecontent Service
' 3. Remove .dbx, .lck and .log files from DataFolder
' 4. restart the service
' 5. Restore the database
Dim fileNewest
Dim fso
Set fso = WScript.CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
'Set ImportFldr = fso.GetFolder("C:\Program Files (x86)\XyEnterprise\SDL LiveContent\data\Import")
Set ImportFldr = fso.GetFolder("C:\Program Files\XyEnterprise\SDL LiveContent\data\export")
'Set DataFldr = fso.GetFolder("C:\Program Files (x86)\XyEnterprise\SDL LiveContent\data")
Set DataFldr = fso.GetFolder("C:\Program Files\XyEnterprise\SDL LiveContent\data")
For Each aFile In ImportFldr.Files
sExtension = fso.GetExtensionName(aFile.Name)
If sExtension = "log" Then
'Msgbox "The file extension is a " & sExtension
Else
'Msgbox "The file extension is a " & sExtension
If fileNewest = "" Then
Set fileNewest = aFile
Else
'If fileNewest.DateCreated < aFile.DateCreated Then
If CDate(fileNewest.DateCreated) < CDate(aFile.DateCreated) Then
Set fileNewest = aFile
End If
End If
End If
Next
Msgbox "The Newest File in the folder is " & fileNewest.Name & chr(13) & "Size: " & fileNewest.Size & " bytes" & chr(13) & "Was last modified on " & FileNewest.DateLastModified
' Change to /Data
'WScript.Echo WshShell.CurrentDirectory
WshShell.CurrentDirectory = DataFldr
'WScript.Echo WshShell.CurrentDirectory
' Stop the Livecontent service
strComputer = "."
Dim objService
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery _
("Select * from Win32_Service where Name = 'LiveContent'")
For Each objService in colServiceList
WScript.Echo objService.State
If objService.State = "Running" Then
objService.StopService()
'Wscript.Sleep 5000
End If
Next
'Dim objShell
'Set objShell = CreateObject("WScript.Shell")
'objShell.Run "%comspec% /k c: & cd ""C:\Program Files (x86)\XyEnterprise\SDL LiveContent\"" & """"loaddb RESTORE -'Dlc.file=C:\PROGRA~2\XYENTE~1\SDLLIV~1\data\Import\" & fileNewest.Name & " -Dlc.pswd=N2kAs72z"""""
LATEST EDIT
I have taken your code and still can't get it to work. I noticed that the line:
Set objWMIService = GetObject("winmgmts:\" & strComputer & "\root\cimv2")
was missing a \ at "winmgmts:\" which I have added and I like your check to see if there is an (x86) directory as I am testing this on a 32bit server but will move it over to a 64 when it is ready so that will work nicely.
Also this section didn't work:
If fso.FolderExists( "C:\Program Files (x86)\XyEnterprise\SDL LiveContent\data" ) Then
Set DataFldr= fso.GetFolder("C:\Program Files (x86)\XyEnterprise\SDL LiveContent\data")
Else If fso.GetFolder("C:\Program diles\XyEnterprise\SDL LiveContent\data") Then
Set DataFldr= fso.GetFolder("C:\Program diles\XyEnterprise\SDL LiveContent\data")
End If
But did if I changed the ElseIf fso.GetFolder to fso.FolderExists
The script runs fine if I comment out Line 78
objService.StopService()
But as soon as I uncomment it I get an error:
Line: 78
Char: 9
Error: Not found
Code: 80041002
Source: SWbemObjectEx
But the Service can be found as the line: WScript.Echo objService.State Echos its state to the screen.
Really confuzzled now.
' 1. Check that the latest backup zip exists and store its name in LBZ (LatestBackupZip)
' 2. Stop the Livecontent Service
' 3. Remove .dbx, .lck and .log files from DataFolder
' 4. restart the service
' 5. Restore the database
Dim fileNewest
Dim ImportFldr
Dim DataFldr
Dim fso
Set fso = WScript.CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
If fso.FolderExists( "C:\Program Files\XyEnterprise\SDL LiveContent\data\Import" ) Then
Set ImportFldr = fso.GetFolder("C:\Program Files\XyEnterprise\SDL LiveContent\data\Import")
Else
WScript.Echo "Warning: Import Directory can not be found"
End If
If fso.FolderExists( "C:\Program Files\XyEnterprise\SDL LiveContent\data\export" ) Then
Set ImportFldr = fso.GetFolder("C:\Program Files\XyEnterprise\SDL LiveContent\data\export")
Else
WScript.Echo "Warning: Export Directory can not be found"
End If
If fso.FolderExists( "C:\Program Files\XyEnterprise\SDL LiveContent\data" ) Then
Set DataFldr= fso.GetFolder("C:\Program Files\XyEnterprise\SDL LiveContent\data")
Else
WScript.Echo "Warning: Data Directory can not be found"
End If
For Each aFile In ImportFldr.Files
sExtension = fso.GetExtensionName(aFile.Name)
If sExtension = "log" Then
'Msgbox "The file extension is a " & sExtension
Else
'Msgbox "The file extension is a " & sExtension
If fileNewest = "" Then
Set fileNewest = aFile
Else
If fileNewest.DateCreated < aFile.DateCreated Then
If CDate(fileNewest.DateCreated) < CDate(aFile.DateCreated) Then
Set fileNewest = aFile
End If
End If
End If
End If
Next
'Msgbox "The Newest File in the folder is " & fileNewest.Name & chr(13) & "Size: " & fileNewest.Size & " bytes" & chr(13) & "Was last modified on " & FileNewest.DateLastModified
' Change to /Data
WScript.Echo WshShell.CurrentDirectory
WshShell.CurrentDirectory = DataFldr
WScript.Echo WshShell.CurrentDirectory
' Stop the Livecontent service
strComputer = "."
Dim objService
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery _
("Select * from Win32_Service where Name = 'LiveContent'")
For Each objService in colServiceList
WScript.Echo objService.State
If objService.State = "Running" Then
objService.StopService()
WScript.Echo objService.State
Wscript.Sleep 5000
End If
Next
EDIT 2
After very extensive testing we have come to the conclusion that there is nothing wrong with the script, it is just that this particular service will not stop with this method.
To this end we have moved on and are now using
objShell.Run "sc start LiveContent"
And this works a treat.
Thanks to Brandon for your help.
There are a couple of minor issues:
1.) Not checking for if a folder exists for calling get folder, this is what was causing your 'Not Found' error.
2.) Non-matching If ... Then & End statements in your file loop. (I would probably choose a better editor for vbscript, programmers notepad and notepad++ are very useful.)
3.) The StartService() / StopService() mix-up I mentioned previously.
' 1. Check that the latest backup zip exists and store its name in LBZ (LatestBackupZip)
' 2. Stop the Livecontent Service
' 3. Remove .dbx, .lck and .log files from DataFolder
' 4. restart the service
' 5. Restore the database
Dim fileNewest
Dim fso
Set fso = WScript.CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
Dim ImportFldr
If fso.FolderExists( "C:\Program Files (x86)\XyEnterprise\SDL LiveContent\data\Import" ) Then
Set ImportFldr = fso.GetFolder("C:\Program Files (x86)\XyEnterprise\SDL LiveContent\data\Import")
Else If fso.FolderExists( "C:\Program Files\XyEnterprise\SDL LiveContent\data\export" ) Then
Set ImportFldr = fso.GetFolder("C:\Program Files\XyEnterprise\SDL LiveContent\data\export")
End If
Dim DataFldr
If fso.FolderExists( "C:\Program Files (x86)\XyEnterprise\SDL LiveContent\data" ) Then
Set DataFldr= fso.GetFolder("C:\Program Files (x86)\XyEnterprise\SDL LiveContent\data")
Else If fso.GetFolder("C:\Program diles\XyEnterprise\SDL LiveContent\data") Then
Set DataFldr= fso.GetFolder("C:\Program diles\XyEnterprise\SDL LiveContent\data")
End If
For Each aFile In ImportFldr.Files
sExtension = fso.GetExtensionName(aFile.Name)
If sExtension = "log" Then
'Msgbox "The file extension is a " & sExtension
Else
'Msgbox "The file extension is a " & sExtension
If fileNewest = "" Then
Set fileNewest = aFile
Else
If fileNewest.DateCreated < aFile.DateCreated Then
If CDate(fileNewest.DateCreated) < CDate(aFile.DateCreated) Then
Set fileNewest = aFile
End If
End If
End If
End If
Next
Msgbox "The Newest File in the folder is " & fileNewest.Name & chr(13) & "Size: " & fileNewest.Size & " bytes" & chr(13) & "Was last modified on " & FileNewest.DateLastModified
' Change to /Data
'WScript.Echo WshShell.CurrentDirectory
WshShell.CurrentDirectory = DataFldr
'WScript.Echo WshShell.CurrentDirectory
' Stop the Livecontent service
strComputer = "."
Dim objService
Set objWMIService = GetObject("winmgmts:\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery _
("Select * from Win32_Service where Name = 'LiveContent'")
For Each objService in colServiceList
WScript.Echo objService.State
If objService.State = "Running" Then
objService.StopService()
'Wscript.Sleep 5000
End If
Next
'Dim objShell
'Set objShell = CreateObject("WScript.Shell")
'objShell.Run "%comspec% /k c: & cd ""C:\Program Files (x86)\XyEnterprise\SDL LiveContent\"" & """"loaddb RESTORE -'Dlc.file=C:\PROGRA~2\XYENTE~1\SDLLIV~1\data\Import\" & fileNewest.Name & " -Dlc.pswd=N2kAs72z"""""
After very extensive testing we have come to the conclusion that there is nothing wrong with the script as it starts and stops other services, it is just that this particular service will not stop with this method.
To this end we have moved on and are now using
objShell.Run "sc start LiveContent"
And this works a treat.
Thanks to Brandon for your help.

Resources