How to terminate a process in vbscript
The Win32_Process class provides access to both 32-bit and 64-bit processes when the script is run from a 64-bit command shell.
If this is not an option for you, you can try using the taskkill command:
Just type in the following command: taskkill /f /im (program name) To find out the im of your program open task manager and look at the process while your program is running. After the program has run a process will disappear from the task manager; that is your program.
I know I am late to the game LOL, but this is what I did to kill SmartScreen.
How to Kill Multiple Processes (Tasks) by Name using VBScript?
Let’s say if you have opened quite a few tasks and you decide to close them all at once without manually close them one by one, or kill each process in Task Manager one by one.

I was coding some multi-processing application and at the testing phrases, I accidentally launch more than 30 processors of same kind (same process name). After I stopped the main host application in the Visual Studio, these processes go un-controlled (they are no longer controlled by the host application any more since I stopped the debugger before the host application kills all of them e.g. host application keeps a track of these process IDs and wait for them to finish).
How to Kill Multiple Processors (Tasks) by Name using CMD Tool TaskKill ?
These is simply using the command line tool taskkill
The /F stands for ‘Force’, and /IM stands for ‘Image Name’ where you can specify the name of the process. You can also use tasklist to get a list of current running processes.
The VBScript to Kill Multiple Processors (Tasks) by Name
VBScript isn’t dead. VBScript is perfect for system administration and it has been supported every since Win98. The following VBScript function kills all processes by given Image Name.
Как на VBScript убить процесс?
Система WinXP.
раз в 5 минут WinSCP синхронизирует файлы и запускает этот скрипт.
Скрипт заходит в папку, и по очереди отправляет все файлы на печать (в моём случае все они pdf).
Покопипастив я сотворил вот такой скрипт
Однако получается, что скрипт доходит до Call gShell.Run(s,0,true), адобридер запускается первый файл на печать уходит и всё, дальше ничего не происходит, пока руками окошко ридера не закроешь.
Может кто подсказать как эту проблему разрешить?
- Вопрос задан более трёх лет назад
- 2628 просмотров
Оценить 1 комментарий
- Вконтакте
‘pinter_PDF.vbs
‘Автоматическая печать PDF-файлов, появляющихся в определенной папке
‘Установите программу SumatraPDF www.softportal.com/software-7568-sumatra-pdf.html
‘Глобальные переменные
Set gFSO = CreateObject(«Scripting.FileSystemObject»)
Set gShell = CreateObject(«WScript.Shell»)
‘Папка, в которой скрипт ждет PDF-файлы (к этой папке (папкам) д.б. дан доступ по сети)
gWatchFolder = «E:\»
‘Основной цикл
While true
Set lFolder = gFSO.GetFolder(gWatchFolder)
Set lFiles = lFolder.Files
WScript.Sleep(10000)
For Each lFile In lFiles
‘ msgbox(gWatchFolder)
‘msgbox(lFile.Name)
PrintFile(gWatchFolder & lFile.Name)
Next
‘Функция печати конкретного pdf-файла
Sub PrintFile(pFileName)
‘Ждем некоторе время (пока файл до конца запишется)
WScript.Sleep(10)
‘msgbox(pFileName)
‘Укажите путь к программе SumatraPDF
s = «»»C:\Program Files\SumatraPDF\SumatraPDF.exe»» -exit-on-print -print-to-default «»» & pFileName & «»»»
‘msgbox (s)
Call gShell.Run(s,0,true)
‘msgbox(pFileName)
WScript.Sleep(10)
gFSO.DeleteFile(pFileName)
If gFSO.FileExists(pFileName) Then
‘Мало ли чего может случиться, лучше пусть у Иван Иваныча перестанет печатать, чем один файл много раз уйдет на принтер
msgbox(«Не удалось удалить файл » & pFileName & «! Позвоните компьютерщику»)
WScript.Quit
‘Else
‘Пока не реализовано
‘ToLog(«Файл » & lFileName & » удален.»)
End If
End sub
‘Доделывал чужое под себя +7 902 44 00 00 6 Компьютерщик www.2133790.Ru
‘брал исходник здесь https://habrahabr.ru/post/112404/ и спасибо автору за ответы на мои вопросы
‘отсюда autoit-script.ru/index.php?topic=21264.0
‘и отсюда www.cyberforum.ru/vbscript-wsh/thread1445205.html
The last command will open a new Adobe Reader window, print the PDF file and then terminate its window unless that window happens to be the only Adobe Reader window left: at least one Adobe Reader window will be left open.
WMI – Stop Process
If ever you wish to stop or terminate a Windows process, then this is the page for you. Before you begin killing processes, you may wish to list processes running on a the Windows Server 2003 or XP computer. Task Manager is a great utility to match the names of the programs with their processes, you would not want to inadvertently kill the wrong process!
Topics for VBScript Kill Process
Scenario – Why you would want to Terminate a Process?
Perhaps you wish to restart a process, if so, then obviously you need to stop the process before you can start it again. Before the WMI script, can stop the program you need to know the precise name of the corresponding program. One way to investigate the names would be to Launch Task Manager, select the Application tab, right-click the Task and then choose, Go to Process. Examples of processes that you could terminate include, spoolsv.exe, outlook.exe.
Another reason why you may wish to investigate, then kill processes is if a virus manages to launch itself as a process. Once you spot the impostor, then the next step is to create a WMI script, which terminates that virus \ process.
Example 1 – WMI Script to Terminate a Process on the Local Machine
The purpose of this script is to terminate a process on the local Windows machine. Think of this script as a preliminary script leading the main event in Example 2.
Prerequisites for Your WMI Stop Process Script
Run this script on Windows Server 2003 or XP. Naturally, if the named process does not exist, there is nothing for the script to terminate. Therefore, you need to start the process referenced on line 9, in my example this process (program) is calc.exe. Consider running my StartProcessScript first.
Note the .terminate method does not work with NT 4.0 or Windows 9x machines.
Instructions for VBScript to Terminating a Process
- Copy and paste the example script below into notepad or a VBScript editor.
- Save the file with a .vbs extension, for example: ProcessKill.vbs
- Double click ProcessKill.vbs and check Task Manger, Application Tab. You may actually wish to start both Calc.exe and Task manager before your run the script.
Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = " & strProcessKill )
For Each objProcess in colProcess
objProcess.Terminate()
Next
WSCript.Echo "Just killed process " & strProcessKill _
& " on " & strComputer
WScript.Quit
‘ End of WMI Example of a Kill Process
WMI Stop Process Tutorial – Learning Points
From a WMI Perspective
1) This script builds on the basic WMI command in Example 1. The heart of the script is the Win32_Process. Once we have selected the strProcessKill, then we call for the .Terminate method to close the program without issuing any warning to the user.
From a VBScript Perspective
2) Study the VBScript syntax used just before the variable strProcessKill:
("Select * from Win32_Process Where Name = " & strProcessKill). For example, see where the speech marks end in relation to the bracket.
3) Although the script only terminates one process, it still has to loop through all the running processes to select the process = strProcessKill. For Each… In… Next handles this scripting structure.
Guy Recommends: WMI Monitor and It’s Free!
Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft’s operating systems. Fortunately, SolarWinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your scripts.
Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory or Exchange Server. Give this WMI monitor a try – it’s free.
Example 2 – WMI Script to Terminate a Process on a Distant Machine
This script builds on Example 1 and adds the ability to terminate a process on a remote machine.
Prerequisites for your WMI Script
Naturally, if the named process does not exist, there is nothing for the script to terminate. Therefore, you need to start the process referenced on line 9, in my example this process (program) is calc.exe.
Note the .terminate method does not work with NT 4.0 or Windows 9x machines.
Instructions for Terminating a Process
- Copy and paste the example script below into notepad or a VBScript editor.
- Save the file with a .vbs extension, for example: ProcessKill.vbs
- Double click ProcessKill.vbs and check processes in Task Manger, there should be no calc.exe.
‘ ProcessKillRemote.vbs
‘ Sample VBScript kill process
‘ Author Guy Thomas https://computerperformance.co.uk/
‘ Version 2.9 – December 2010
‘ ———————— ——————————-‘
Option Explicit
Dim objWMIService, objProcess, colProcess
Dim strComputer, strProcessKill, strInput
strProcessKill = "’calc.exe’"
‘ Input Box to get name of machine to run the process
Do
strComputer = (InputBox(" ComputerName to Run Script",_
"Computer Name"))
If strComputer <> "" Then
strInput = True
End if
Loop until strInput = True
Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = " & strProcessKill )
For Each objProcess in colProcess
objProcess.Terminate()
Next
WSCript.Echo "Just killed process " & strProcessKill _
& " on " & strComputer
WScript.Quit
‘ End of WMI Example of a Kill Process
Guy Recommends: The Free Config Generator
SolarWinds’ Config Generator is a free tool, which puts you in charge of controlling changes to network routers and other SNMP devices. Boost your network performance by activating network device features you’ve already paid for.
Guy says that for newbies the biggest benefit of this free tool is that it will provide the impetus for you to learn more about configuring the SNMP service with its ‘Traps’ and ‘Communities’. Try Config Generator now – it’s free!
WMI Tutorial – VBScript Stop Process
From a WMI perspective
1) This script builds on the basic WMI command in Example 1. The heart of the script is the Win32_Process. Once we have selected the strProcessKill, then we call for the .Terminate method to close the program without issuing any warning to the user.
From a VBScript perspective
2) Study the VBScript syntax used just before the variable strProcessKill:
("Select * from Win32_Process Where Name = " & strProcessKill). For example, see where the speech marks end in relation to the bracket.
3) Although the script only terminates one process, it still has to loop through all the running processes to select the process = strProcessKill. For Each… In… Next handles this scripting structure.
Example PowerShell – Get Stop-Process
All I need is to pipe ‘Get-Process notepad’ into Stop-Process The result is its output becomes the input for Stop-Process. Here is the working example:
# PowerShell Kill Process
Clear-Host
Get-Process notepad | Stop-Process
Learning Points
Note 2: It’s all down to the (|) pipe.
Note 3: The knack is to employ Get-Process to get a grip on the named process object, then we use Stop-Process to remove it from the list of running programs.
Summary of VBScript Kill Process
This page builds logically and is based on the assumption you have a Windows Server or client machine. We start with a simple WMI script which lists the processes (programs) then echoes the result to the screen. The second example introduces the powerful .terminate method which kills the named program without warning the users.