Set interval in vbscript - vbscript

I want to set interval time in vbscript
Following is my code
Set objWord = CreateObject("Word.Application")
endTime= Timer()
'Set visibilty for the client application
objWord.Visible = True
WScript.Sleep 1000
'Close MS word process
objWord.Quit
I found WScript.Sleep 1000 or WScript.Sleep(1000) 1000 is in millisecond
but both of them are not working fine, I am using window7

Quick-and-dirty batch command is the safest and surest (though not the most accurate) way to get a delay.
' Get a 10 seconds delay
Delay 10
Sub Delay( seconds )
Dim wshShell
Set wshShell = CreateObject( "WScript.Shell" )
wshShell.Run "ping -n " & ( seconds + 1 ) & " 127.0.0.1", 0, True
Set wshShell = Nothing
End Sub
As seen on Rob van der Woude's Scripting Page .Here you can also find lot of good scripts

Related

Set timer in VBS [duplicate]

This question already has answers here:
Close program opened by vbs script with same script
(2 answers)
Closed 11 months ago.
I want to modify the script to launch the calculator app for 2 minutes then close it. The script can launch the app only. Please help.
Set colMonitoredEvents = GetObject("winmgmts:")._
ExecNotificationQuery("SELECT * FROM Win32_PowerManagementEvent")
Do
Set strLatestEvent = colMonitoredEvents.NextEvent
If strLatestEvent.EventType = 4 Then
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_Process")
For Each objItem in colItems
If objItem.name = "Calculator.exe" then objItem.terminate
Next
ElseIf strLatestEvent.EventType = 7 Then
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "calc.exe", 1, false
End If
Loop
I want to modify it to launch and close the calculator.exe.
This is accomplished simply with Sleep and TaskKill. Note that, starting probably with Windows 8, the calculator is a UWP app and Calc.exe is used to launch it, but Calculator.exe is the process name to kill it. On Windows 7, it would be Calc.exe for both.
Set oWSH = CreateObject("Wscript.Shell")
oWSH.Run "Calc.exe", 1, False
WScript.Sleep 120000 'two minutes
oWSH.Run "TaskKill /im Calculator.exe /f", 0, False
If you want to retain the capability of the original script, which kills calculator when the computer goes to sleep and restarts it on wake, and add a two minute delay before the kill, that would be done like this:
Set oWSH = CreateObject("Wscript.Shell")
Set colMonitoredEvents = GetObject("winmgmts:").ExecNotificationQuery("SELECT * FROM Win32_PowerManagementEvent")
Do
Set strLatestEvent = colMonitoredEvents.NextEvent
If strLatestEvent.EventType = 4 Then
WScript.Sleep 120000 'two minutes
oWSH.Run "TaskKill /im Calculator.exe /f", 0, False
ElseIf strLatestEvent.EventType = 7 Then
oWSH.Run "calc.exe", 1, False
End If
WScript.Sleep 500
Loop
Note that I added a .5 second delay in the loop to prevent unnecessary CPU load.

Issues trying to close a bat file from a vbs script

i'm trying to help my little brother with a vbs script file, i've never used vbs, and i'm having serious issues on finding out how to end a bat file that i've opened with the vbs script after 2 seconds
I've tried terminate but it doesn't work, even running another shell with taskkill and the name of process but nothing
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "C:\\Users\me\Desktop\Samples\t.bat"
Wscript.Sleep 2000`
I would like the bat file to close itself after 2 seconds
Use the Exec command instead of Run.
https://ss64.com/vb/exec.html
"Unlike .Run method, .Exec returns an object which returns additional information about the process started."
This example uses cmd.exe /k (the /k will keep the cmd.exe window open, which will be killed after your 2 second timeout even if your bat script logic finishes before that)
Dim shll : Set shll = CreateObject("WScript.Shell")
Set Rt = shll.Exec("cmd.exe /k C:\Temp\test.bat") : wscript.sleep 2000 :
Rt.Terminate
If you want to return the output of the bat script you will need to read this WScript.Shell.Exec - read output from stdout, and use logic similar to:
Const WshRunning = 0
Const WshFinished = 1
Const WshFailed = 2
strCommand = "C:\Temp\test.bat"
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec(strCommand)
Do While oExec.Status = 0
WScript.Sleep 1000
If Not oExec.StdErr.AtEndOfStream Then
vErrStr = vErrStr & oExec.StdErr.ReadAll
End If
If Not oExec.StdOut.AtEndOfStream Then
vOutStr = vOutStr & oExec.StdOut.ReadAll
End If
Loop
WScript.StdOut.Write(vErrStr)
WScript.Echo(vOutStr)
It all depends on what your bat file is doing really, and the reason you need to kill it after x seconds.
Edit:
Because your batch file is a continuous loop, it may confuse ReadAll of the output stream. You might be best using something such as (note that you will not see real-time output):
Dim strCommand : strCommand = "C:\Temp\test.bat"
Dim WshShell : Set WshShell = CreateObject("WScript.Shell")
'execute command
Dim oExec : Set oExec = WshShell.Exec(strCommand)
'wait 2 seconds
WScript.Sleep 2000
'terminate command
oExec.terminate
'get output
wscript.echo oExec.StdOut.ReadAll
Set oExec = Nothing
Set WshShell = Nothing

Make vbs wait until a time and then run a batch script

I want to make a vbscript that waits until its 11:00AM and when it turns that time i want it to launch a batch script. I only know how to use
WScript.Sleep
But i want to make it run at a certain time.
Check system time with Now():
Dim time, WshShell
Set WshShell = CreateObject("WScript.Shell")
time = Now()
hm = Minute(time) + 100 * Hour(time)
' Only execute between 11:00AM and 11:30AM
While hm < 1100 Or hm > 1130
WScript.Sleep 2
time = Now()
hm = Minute(time) + 100 * Hour(time)
Wend
' Do your job here
WshShell.Run "some.bat", , False

VBScript not working when PC is locked

I'm running a VBScript that communicates to an exe file in Windows 7.
The VBScript works great!
The issues I have, is that once the PC has been in locked, goes to sleep or hiberation the VBScript doesn't communicate with the exe application.
The VBScript is running (I have a log that tells me every time a loop is complete, but its not communicating to the exe.
Below is code that is not working when the PC is locked.
Set WSHShell = WScript.CreateObject("WScript.Shell")
' info for exporting data
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Dim fso, MyFile, FileName, TextLine, cycles
Dim I
I = 0
Dim n
n = .1 'how often the program saves the data (in minutes)
cycles = 2 'how many times it will save
FileName = "C:\Users\Desktop\new.txt" 'location where the log file will save
Dim sl
sl = n * 60000 'change from seconds to ms for the sleep function
Set fso = CreateObject("Scripting.FileSystemObject")
' Open the file for output
Set MyFile = fso.OpenTextFile(FileName, ForAppending, True, TristateTrue)
' Write to the file.
MyFile.WriteLine "Log file for recording data from Yokogawa MX100 (" & cycles
& " cycles)"
WSHShell.Run "MXStandardE.exe"
WScript.Sleep 1000
WSHShell.AppActivate "MXStandardE.exe"
WScript.Sleep 1000
Do while I < cycles
a = Now()
WScript.Sleep 1000
WSHShell.Run "MXStandardE.exe"
WScript.Sleep 1000
WSHShell.AppActivate "MXStandardE.exe"
WScript.Sleep 1000
WSHShell.SendKeys "%A"
WScript.Sleep 1000
WSHShell.SendKeys "{DOWN}"
WScript.Sleep 1000
WSHShell.SendKeys "{ENTER}"
I = I + 1
MyFile.Writeline I & " of " & cycles & " at " & a & " --time of each cycle is
" & n & " minutes"
WScript.Sleep sl 'when sl is used loop time is in minutes
Loop
MyFile.Close
MsgBox ("Script has completed")
As Ansgar already said, it's pretty obvious that nothing will work while the PC sleeps or hibernates. In the case where the PC is locked, techniques that rely on window management or direct input such as SendKeys won't work as expected, because the user's session, along with user-level applications, is essentially shelved to make way for the login screen or another user.
You might want to do some research into the SendMessage/PostMessage API, or you can stop using VBScript and replace it with a Scheduled Task or system service that runs using a local service account, assuming you just want to execute an exe without any UI interaction.
The question is: do you need to go under hibernation or pc suspension? If not, you should simply configure or turn off those settings. By only locking the session, the vbscript should be run and generate an outpout without any trouble. By checking and configuring advanced windows energy settings it might help you solving this.

How to output Command prompt to a log file using VBScript

I'm not a programmer so I don't want to overly irritate the fine folk in this forum. My issue is that I would like to use VBScript to Telnet into a Linux device, issue a DF command and output all response to a log file which I can parse later. I originally found a method to successfully Telnet but I have have been experimenting without success regarding the text file output requirement. The following code certainly does not work but I am wondering if I am even close to the correct method?
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("cmd /c dir")
WshShell.run"cmd" '*** open command window ***
WScript.Sleep 250
WshShell.SendKeys("{Enter}")
WshShell.SendKeys"telnet 10.13.2.2"
WshShell.SendKeys("{Enter}")
WScript.Sleep 2000
WshShell.SendKeys"root"
WshShell.SendKeys("{Enter}")
WScript.Sleep 1500
WshShell.SendKeys"password"
WshShell.SendKeys("{Enter}")
WScript.Sleep 1500
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = objFSO.OpenTextFile("C:\VBSmemSize.txt", 2, True)
WshShell.SendKeys"df /mnt/cf"
WshShell.SendKeys("{Enter}")
Do
strFromProc = oExec.Stdout.Readline()
WScript.Echo strFromProc
Loop While Not objLogFile.StdOut.atEndOfStream
You can capture output from external commands but not at the same time interact with them like you do with sendkeys. Here an example of what works
Function ExecPing(strTarget)
Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec("ping -n 2 -w 1000 " & strTarget)
strPingResults = LCase(objExec.StdOut.ReadAll)
If InStr(strPingResults, "antwoord van") Then '"reply from" in E
WScript.Echo VbCrLf & strTarget & " responded to ping."
ExecPing = True
Else
WScript.Echo VbCrLf & strTarget & " did not respond to ping."
ExecPing = False
End If
End Function
ExecPing pcname

Resources