I made a simple vbs script to kill a process but need to loop it.
Dim oShell : Set oShell = CreateObject("WScript.Shell")
WScript.Sleep 5000
oShell.Run "taskkill /im firefox.exe", , True
loop
Dim oShell : Set oShell = CreateObject("WScript.Shell")
Do
WScript.Sleep 5000
oShell.Run "taskkill /im firefox.exe", , True
loop
Will kill firefox every 5 secs forever.
Related
My script launches a MS Edge window and then tries to log into Netflix with my credentials. The problem is, at times, the browser window comes up behind the CMD console and the script doesn't work.
How do I launch the browser in the foreground or bring it to the foreground after it's launched?
<!-- :
rem #Echo Off
Set "usr_name=#####"
Set "usr_pass=#####"
%SystemRoot%\System32\cscript.exe //NoLogo "%~f0?.wsf" "%browser%" "%usr_name%" "%usr_pass%"
Exit /B
-->
<Job>
<Script Language="VBScript">
Dim ObjShell, MyChrome
Set ObjShell = WScript.CreateObject("WScript.Shell")
MyChrome = Chr(34) & WScript.Arguments(0) & Chr(34)
ObjShell.Run MyChrome & "--app=""https://www.netflix.com/login""", 1
WScript.Sleep 5000
ObjShell.SendKeys "{TAB}"
ObjShell.SendKeys "{TAB}"
ObjShell.SendKeys(WScript.Arguments(1))
ObjShell.SendKeys "{TAB}"
ObjShell.SendKeys(WScript.Arguments(2))
ObjShell.SendKeys "{ENTER}"
WScript.Sleep 6000
ObjShell.SendKeys "{ESCAPE}"
ObjShell.SendKeys "{TAB}"
WScript.Sleep 1000
ObjShell.SendKeys "{TAB}"
WScript.Sleep 1000
ObjShell.SendKeys "{ENTER}"
WScript.Sleep 6000
ObjShell.SendKeys "%{F4}"
</Script>
</Job>
Scripts that depend on SendKeys are notoriously unreliable. A more reliable approach is to control the browser with Seleniumbasic and Chrome driver or use WebView2 in a C# program. Barring that, one option for adding window control functionality to your existing script is to use the command line tool Cmdow. For example:
ObjShell.Run "cmdow ""Netflix*"" /MAX",1,False
Update:
You can also try the built-in AppActivate method:
ObjShell.AppActivate "Netflix"
The solution to to use a powershell cmdlet to minimize all windows before running the script that launches the browser.
'''powershell -command "(new-object -com shell.application).minimizeall()'''
I am trying to automate the Group Policy editing process as much as possible.
I have the following script to spawn the gpedit.msc process but it's window goes out of focus as soon as it opens:
FINDSTR /E "'VbsCode" %~f0 > %temp%\~temp.vbs
CSCRIPT //NOLOGO %temp%\~temp.vbs
Sub GPEditOptions 'VbsCode
On Error Resume Next 'VbsCode
Set WshShell = WScript.CreateObject("WScript.shell") 'VbsCode
WshShell.Visible = False 'VbsCode
WshShell.Run "gpedit.msc",0 'VbsCode
:: WshShell.AppActivate "Local Group Policy Editor" 'VbsCode
End Sub 'VbsCode
GPEditOptions 'VbsCode
:: WScript.Quit 0 'VbsCode
How can I AppActivate the window that has been opened by the newly spawned gpedit.msc process ? Specifically how to know what's the name/title of that window that has been opened ? "Local Group...Editor" doesn't work.
I think I eventually figured out, how to approach this problem. There are different types of processes.
In this case, I first need to select the Microsoft Management Console window, since it's the parent process which spawns the actual "Local Group Policy Editor" child process.
So this code does the job of selecting the first Windows Component starting with letter "W" by sending a ton of keys priorly, and yes you do need Administrator elevation for proper selection of options in the gpedit.msc window:
#echo off
net file 1>nul 2>nul
if not '%errorlevel%' == '0' (
powershell Start-Process -FilePath "%0" -ArgumentList "%cd%" -verb runas >nul 2>&1
exit /b
)
cd /d %1
FINDSTR /E "'VbsCode" %~f0 > %temp%\~temp.vbs
CSCRIPT //NOLOGO %temp%\~temp.vbs
Sub GPEditOptions 'VbsCode
On Error Resume Next 'VbsCode
Set WshShell = WScript.CreateObject("WScript.shell") 'VbsCode
WshShell.Visible = False 'VbsCode
WshShell.Run "gpedit.msc",0 'VbsCode
WScript.Sleep 500 : WshShell.AppActivate "Microsoft Management Console" 'VbsCode
WScript.Sleep 500 : WshShell.AppActivate "Local Group Policy Editor" 'VbsCode
WScript.Sleep 500 : WshShell.sendKeys "% x{TAB}{ENTER}" 'VbsCode
WScript.Sleep 500 : WshShell.sendKeys "{TAB}{TAB}{TAB}{TAB}" 'VbsCode
WScript.Sleep 500 : WshShell.sendKeys "{DOWN}{DOWN}{ENTER}" 'VbsCode
WScript.Sleep 500 : WshShell.sendKeys "{TAB}{TAB}{TAB}{TAB}" 'VbsCode
WScript.Sleep 500 : WshShell.sendKeys "{DOWN}{DOWN}{DOWN}{DOWN}" 'VbsCode
WScript.Sleep 500 : WshShell.sendKeys "{DOWN}{DOWN}{ENTER}" 'VbsCode
WScript.Sleep 500 : WshShell.sendKeys "{TAB}{TAB}{TAB}{TAB}{W}" 'VbsCode
End Sub 'VbsCode
GPEditOptions 'VbsCode
WScript.Quit 0 'VbsCode
Hope this helps anyone facing similar issue.
There is no need of sending bunch of keys and getting the Group policy editor window title.
Actually every group policy setting has equivalent registry keys. And registry can be edited easily from VBScript. To find the equivalent registry key for the group policy setting:
Download a tool named Process Monitor from SysInternals.
Run it and click Filter > Filter.
Now create two filters like: "Process name" - "is" - "mmc.exe" - then "include" and "Operation" - "is" - "RegSetValue" - then "Include".
Now edit the group policy setting and the registry key will appear in Process monitor.
And Function to edit registry in VBScript:
Function RegSetValue(regkey,value)
Dim WshShell
Set WshShell = CreateObject("Wscript.Shell")
WshShell.RegWrite(regkey,value)
End Function
I'm looking to make a batch file that will close a program at a set time after opening it. So, for example, if I open my email program, the batch file will be triggered, and after two minutes, my email will automatically close. If possible, I would also like the command window to open hidden. I tried working with the Event Logger and the Task Scheduler, but I got nowhere fast.
Any suggestions?
Thanks!
Run Command hidden
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd /k dir c:\windows\*.*", 0, false
This detects when an app exits. Here when notepad exits it restarts it. You can alter it to process starts, stops, or both. Win32_ProcessStopTrace, Win32_ProcessStartTrace, and Win32_ProcessStartStopTrace.
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set objEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM Win32_ProcessStopTrace")
Do
Set objReceivedEvent = objEvents.NextEvent
msgbox objReceivedEvent.ProcessName
If lcase(objReceivedEvent.ProcessName) = lcase("Notepad.exe") then
Msgbox "Process exited with exit code " & objReceivedEvent.ExitStatus
WshShell.Run "c:\Windows\notepad.exe", 1, false
End If
Loop
This goes through the list of running processes and if Calculator terminates it.
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_Process")
For Each objItem in colItems
'msgbox objItem.ProcessID & " " & objItem.CommandLine
If objItem.name = "Calculator.exe" then objItem.terminate
Next
To have a script wait. From Help at https://www.microsoft.com/en-au/download/details.aspx?id=2764
Suspends script execution for a specified length of time, then continues execution.
object.Sleep(intTime)
object
WScript object.
intTime
Integer value indicating the interval (in milliseconds) you want the script process to be inactive.
So wscript.sleep 120000 is two minutes
I'll leave you to tie it together.
I'm writing a batch script which runs a few programs. As each program finishes what it's doing it waits for either the user to close it out, moving on to the next, or being closed by taskkill after a timeout of so many seconds. If I consider the main script as MAIN, the program as TASK and the timer as KILLER. The MAIN starts the TASK and KILLER at (about) the same time. TASK does what it's supposed to and KILLER waits 600 seconds before killing TASK. However if TASK were closed by the user it should kill the KILLER and return to MAIN without user interaction. However using ping or timeout I still have to wait for the timer to expire before the batch will actually close. I would like not to have my desktop littered with command windows that'll do nothing. Is there any way around this?
You can use something like this
#echo off
setlocal enableextensions disabledelayedexpansion
start "" task.exe
call :timeoutProcess "task.exe" 300
start "" task.exe
call :timeoutProcess "task.exe" 300
exit /b
:timeoutProcess process timeout [leave]
rem process = name of process to monitor
rem timeout = timeout in seconds to wait for process to end
rem leave = 1 if process should not be killed on timeout
for /l %%t in (1 1 %~2) do (
timeout /t 1 >nul
tasklist | find /i "%~1" >nul || exit /b 0
)
if not "%~3"=="1" taskkill /f /im "%~1" >nul 2>nul
if %errorlevel% equ 128 ( exit /b 0 ) else ( exit /b 1 )
The timeout logic is moved to a subroutine that will wait until the process ends or the timeout is reached.
Here's a vbs script.
It waits till a program exits, see's if it's notepad, then restarts notepad if it is. Change Win32_ProcessStopTrace to Win32_ProcessStartTrace for program starts, or Win32_ProcessTrace for all starts and stops.
Console scripts are started like so. GUI scripts just execute the script direct. GUI scripts are invisible.
cscript "c:\somefolder\script.vbs"
To wait in a script use wscript.sleep 600000 (milliseconds).
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set objEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM Win32_ProcessStopTrace")
Do
Set objReceivedEvent = objEvents.NextEvent
wscript.echo objReceivedEvent.ProcessName
If lcase(objReceivedEvent.ProcessName) = lcase("Notepad.exe") then
WScript.echo "Process exited with exit code " & objReceivedEvent.ExitStatus
WshShell.Run "c:\Windows\notepad.exe", 1, false
End If
Loop
And this is how to start an invisible command window.
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd /k dir c:\windows\*.*", 0, false
I have batch script,I saved res.bat and run,but it is not Exit when finish run.Help me!!!
echo Set objShell = CreateObject( "WScript.Shell" ) > %TEMP%\sp.vbs
echo Set objSystemEnv = objShell.Environment( "SYSTEM" ) >> %TEMP%\sp.vbs
echo objSystemEnv("Path") = objSystemEnv("Path") ^& ";ABCAA" >> %TEMP%\sp.vbs
cscript.exe /nologo %TEMP%\sp.vbs
del %TEMP%\sp.vbs
cls
Try putting an #exit command at the end of the script.
Or you can try this script:
Dim objShell : Set objShell = CreateObject("WScript.Shell")
Dim objSysEnv : Set objSysEnv = objShell.Environment("SYSTEM")
objSysEnv("PATH") = objSysEnv("PATH") & ";ABCAA"
and save it as vbs. It will run with no window at all. Tested on my PC. I had to clean my path variable since I will not be using it :). It's not bat, but it,s working.
It the end of the code #exit WILL NOT WORK! Try doing just exit or maybe close or stop.