Set timer in VBS [duplicate] - vbscript

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.

Related

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

How to stop a specific script in VBScript

Is there a code to stop a specific script? I've seen a way that allows you to end all scripts using taskkill.
Option Explicit
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "taskkill /f /im Cscript.exe", , True
WshShell.Run "taskkill /f /im wscript.exe", , True
I simply want to end one specific script that is sleeping in a wscript.sleep not every script that is running at a time.
Try below. You need to preserve the ProcessId of the process you want to kill. Below code opens a notepad and kills it. This example shows you how to capture the ProcessId of the script when it was started and then kill it.
Private Sub KillTest()
Dim killCmd
Dim pid
Set WshShell = CreateObject("WScript.Shell")
Set EngineRun = WshShell.Exec("notepad")
pid = EngineRun.ProcessID
killCmd = "taskkill /pid " & CStr(pid)
Set EngineRun = WshShell.Exec(killCmd)
Set EngineRun = Nothing
Set WshShell = Nothing
End Sub

Run a cmd.exe which calls a bat file and wait to finish [duplicate]

This question already has answers here:
VBScript - How to make program wait until process has finished?
(4 answers)
Closed 6 years ago.
I need to be able to run cmd.exe with special privilege to run a bat file and wait until it finishes.
I already managed to open cmd.exe with special privilege but I cannot find a wait until the bat file finishes.
I cannot use WScript.Shell because cmd.exe is opened with special privilege using cimv2.
Dim WMIObj, strHost, intProcessID
On Error Resume Next
strHost = "."
Set WMIObj = GetObject("winmgmts:\\" & strHost & "\root\cimv2:Win32_Process")
If IsObject(WMIObj) Then
WMIObj.Security_.Privileges.AddAsString "SeRestorePrivilege", True
WMIObj.Create "cmd.exe /c cd /d c:\temp && asd.cmd && pause", Null, Null, intProcessID
End If
Set WMIObj = Nothing
Add a loop to wait until the process with PID intProcessID disappears:
Set wmi = GetObject("winmgmts://./root/cimv2")
Do
WScript.Sleep 100
Set p = wmi.ExecQuery("SELECT * FROM W32_Process WHERE ProcessID=" & intProcessID)
Until p.Count = 0

Why does this small vbscript to change desktop background work intermittently, not all the time?

A small VBscript in order to change the desktop background automatically, practically for demo purposes:
dim wshShell
dim sUserName
Set wshShell = WScript.CreateObject("WScript.Shell")
Set oShell = CreateObject("WScript.Shell")
currWallPaper = oShell.RegRead("HKCU\Software\Microsoft\InternetExplorer\Desktop\General\Wallpap erSource")
If currWallPaper = "C:\Users\Utsav\Pictures\493889.png" Then
msgbox "OK1"
sWallPaper = "C:\Users\Utsav\Pictures\336180.png"
ElseIf currWallPaper = "C:\Users\Utsav\Pictures\336180.png" Then
sWallPaper = "C:\Users\Utsav\Pictures\1920-1080-278658.png"
Else
sWallPaper = "C:\Users\Utsav\Pictures\493889.png"
End If
' update in registry
oShell.RegWrite "HKCU\Control Panel\Desktop\Wallpaper", sWallPaper
' let the system know about the change
oShell.Run "%windir%\System32\RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters", 1, True
msgbox "done"
This script works only intermittently, i.e. on executing from command line it will change the background only once in about 4-5 attempts. Any ideas explaining the reason for this behaviour would be most welcome.

Set interval in 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

Resources