What's wrong with my VBscript code? - windows

I write the vbscript code to monitor system starting and ending time but it's not logging in same day 'That means not open and writing the same date file how to solve this
Dim objFS, objFile
Dim crdate,ckdate,fname
Set objFS = CreateObject("Scripting.FileSystemObject")
do
crdate = Day(now) & "-" & Month(now) & "-" & Year(now)
fname = crdate & ".txt"
if (objFS.FileExists(fname)) Then
do
ckdate = Day(now) & "-" & Month(now) & "-" & Year(now)
objFile.WriteLine(Time & "\n")
wscript.sleep 300000
loop until ckdate <> crdate
else
Set objFile = objFS.CreateTextFile(fname)
end if
loop

I found the answer in google that is closing the file with
objFile.Close
Dim objFS, objFile
Dim crdate,ckdate,fname
Set objFS = CreateObject("Scripting.FileSystemObject")
do
crdate = Day(now) & "-" & Month(now) & "-" & Year(now)
fname = crdate & ".txt"
if (objFS.FileExists(fname)) Then
Set objFile = objFS.OpenTextFile(fname, 8, True)
objFile.WriteLine("-------------------------------")
do
ckdate = Day(now) & "-" & Month(now) & "-" & Year(now)
objFile.WriteLine(Time)
wscript.sleep 300000
loop until ckdate <> crdate
objFile.Close
else
Set objFile = objFS.CreateTextFile(fname)
objFile.Close
end if
loop

Windows does this natively... you don't have to reinvent the wheel. You can pull this locally or remotely and more ACCURATELY with the windows events.
PS C:\Users\steve> Get-WinEvent -Log System | where {($_.ID -eq "12" -or $_.ID -eq "13")} | format-table -property Message
Message
-------
The operating system started at system time ?2017?-?01?-?01T00:51:20.610798500Z.
The operating system is shutting down at system time ?2017?-?01?-?01T00:50:53.812034600Z.

Related

Upload and download a file using FTP without ActiveX

I want VBScript to upload and download a file using FTP without using ActiveX program.
Notice please give me download code alone and upload code alone and must upload file not folder.
For example:
Set oShell = CreateObject("Shell.Application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
path = "test.txt"
FTPUpload(path)
Sub FTPUpload(path)
On Error Resume Next
Const copyType = 16
waitTime = 80000
FTPUser = "user"
FTPPass = "pass"
FTPHost = "www.domain.com"
FTPDir = "/htdocs/"
strFTP = "ftp://" & FTPUser & ":" & FTPPass & "#" & FTPHost & FTPDir
Set objFTP = oShell.NameSpace(strFTP)
'objFTP.NewFolder "FTP Backup"
If objFSO.FileExists(path) Then
Set objFile = objFSO.getFile(path)
strParent = objFile.ParentFolder
Set objFolder = oShell.NameSpace(strParent)
Set objItem = objFolder.ParseName(objFile.Name)
Wscript.Echo "Uploading file " & objItem.Name & " to " & strFTP
objFTP.CopyHere objItem, copyType
End If
If objFSO.FolderExists(path) Then
Set objFolder = oShell.NameSpace(path)
Wscript.Echo "Uploading folder " & path & " to " & strFTP
objFTP.CopyHere objFolder.Items, copyType
End If
If Err.Number <> 0 Then
Wscript.Echo "Error: " & Err.Description
End If
WScript.Sleep waitTime
End Sub

Vbscript logging into ftp

I am attempting to log into ftp host and download files. I am not sure how to locate the file as it is stored in directories under the date and will change every day. this is what I have so far
Option Explicit
Dim objFSO, objMyFile, objShell, strFTPScriptFileName, strFilePut
Dim strLocalFolderName, strFTPServerName, strLoginID
Dim strPassword, strFTPServerFolder
strLocalFolderName = "c:\foldername"
strFTPServerName = "ftp.host.com"
strLoginID = "somelogin"
strPassword = "password8"
so after the password how would I log into the date file and locate so for example the file would be under
20130722/filename.ftp
The usual way to do this in VBScript is to generate an FTP script and run that with ftp.exe:
'variable definitions
...
Function qq(str)
qq = Chr(34) & str & Chr(34)
End Function
Set fso = CreateObject("Scripting.FileSystemObject")
Set sh = CreateObject("WScript.Shell")
remoteDir = Year(Date) & Right("0" & Month(Date), 2) & Right("0" & Day(Date), 2)
tempDir = sh.ExpandEnvironmentStrings("%TEMP%")
script = fso.BuildPath(tempDir, "download.ftp")
logfile = fso.BuildPath(tempDir, "ftp.log")
Set f = fso.OpenTextFile(script, 2, True)
f.WriteLine "open" & strFTPServerName & vbNewLine _
& "user" & strLoginID & vbNewLine _
& strPassword & vbNewLine _
& "prompt no" & vbNewLine _
& "lcd " & strLocalFolderName & vbNewLine _
& "cd " & remoteDir & vbNewLine _
& "get cs.ftp" & vbNewLine _
& "bye"
f.Close
rc=sh.Run("%COMSPEC% /c ftp -s:" & qq(script) & " >" & qq(logfile), 0, True)
WScript.Echo "FTP finished with exit code " & rc & "."
fso.DeleteFile script, True
The above should work out of the box. If you're free to install additional software, the FTP client included with ActiveXperts' Network Component might be another option.

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.

Ping script with email in vbs

i know i asked already the question about the ping script but now i have a new question about it :-) I hope someone can help me again.
strText = "here comes the mail message"
strFile = "test.log"
PingForever strHost, strFile
Sub PingForever(strHost, outputfile)
Dim Output, Shell, strCommand, ReturnCode
Set Output = CreateObject("Scripting.FileSystemObject").OpenTextFile(outputfile, 8, True)
Set Shell = CreateObject("wscript.shell")
strCommand = "ping -n 1 -w 300 " & strHost
While(True)
ReturnCode = Shell.Run(strCommand, 0, True)
If ReturnCode = 0 Then
Output.WriteLine Date() & " - " & Time & " | " & strHost & " - ONLINE"
Else
Output.WriteLine Date() & " - " & Time & " | " & strHost & " - OFFLINE"
Set objEmail = CreateObject("CDO.Message")
objEmail.From = "noreply#test.net"
objEmail.To = "test#test.net"
objEmail.Subject = "Computer" & strHost & " is offline"
objEmail.Textbody = strText
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
"smtpadress"
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmail.Configuration.Fields.Update
objEmail.Send
End If
Wscript.Sleep 2000
Wend
End Sub
My problem is now, the mail comes all 2 seconds, when the computer are offline. Can someone show me how to make it with flags? So only one mail comes when its offline?
Thanks for your help.
Use a flag and report only when state changes
FLAG0 = "ON"
While(True)
ReturnCode = Shell.Run(strCommand, 0, True)
If ReturnCode = 0 Then
Output.WriteLine Date() & " - " & Time & " | " & strHost & " - ONLINE"
FLAG0 = "ON"
Else
Output.WriteLine Date() & " - " & Time & " | " & strHost & " - OFFLINE"
IF FLAG0 = "ON" THEN
FLAG0 = "OFF"
Set objEmail = CreateObject("CDO.Message")
...... rest of mailing code
END IF
End If

Ping script with loop and save in a txt

i try to make an Ping script with vbs. I need a Script, that ping (no ping limit, the program will run all the time) a computername in the network every 2 seconds and save the results in a txt file.
For Example:
06/08/2010 - 13:53:22 | The Computer "..." is online
06/08/2010 - 13:53:24 | The Computer "..." is offline
Now i try a little bit:
strComputer = "TestPC"
Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}")._
ExecQuery("select * from Win32_PingStatus where address = '"_
& strComputer & "'")
For Each objStatus in objPing
If IsNull(objStatus.StatusCode) Or objStatus.StatusCode <> 0 Then
..........
Next
And than i don't know how to make it. (I'm new with vbs :-))
I hope some one can help me.
Greeting,
matthias
Try this
Option Explicit
Dim strHost, strFile
strHost = "www.google.com" '"127.0.0.1"
strFile = "C:\Test.txt"
PingForever strHost, strFile
Sub PingForever(strHost, outputfile)
Dim Output, Shell, strCommand, ReturnCode
Set Output = CreateObject("Scripting.FileSystemObject").OpenTextFile(outputfile, 8, True)
Set Shell = CreateObject("wscript.shell")
strCommand = "ping -n 1 -w 300 " & strHost
While(True)
ReturnCode = Shell.Run(strCommand, 0, True)
If ReturnCode = 0 Then
Output.WriteLine Date() & " - " & Time & " | The Computer " & strHost & " is online"
Else
Output.WriteLine Date() & " - " & Time & " | The Computer " & strHost & " is offline"
End If
Wscript.Sleep 2000
Wend
End Sub
You put your pings inside a loop of some kind and then use Wscript.Sleep 2000 to sleep for 2 seconds.
Then you use the File System Object (FSO) to write to a file. Information can be found here.
Edit: Something like this might work:
Const OpenFileForAppending = 8
Dim fso, ts
Set fso = CreateObject("Scripting. FileSystemObject")
While 1 > 0 ' loop forever
Set ts = fso.OpenTextFile("c:\temp\test.txt", OpenFileForAppending, True)
' do your pinging code
'if ok
ts.WriteLine("OK")
'else
ts.WriteLine("Not OK")
'endif
ts.Close()
Wscript.Sleep 2000
Wend

Resources