Stopping Multiple Services Windows 7 using VBScript - vbscript

During my internet searches, I have found a script that is supposed to stop a service. The current script runs, finds the services specified in an array, but doesn't seem to stop them. When the script outputs the services' State, it's still running. Below is the script.
sComputer = "."
aTargetSvcs= Array("mysql","Apache2.4")
Set oWMIService = GetObject("winmgmts:" & "{impersonationlevel=impersonate}!\\" _
& sComputer & "\root\cimv2")
Set cServices = oWMIService.ExecQuery("SELECT * FROM Win32_Service")
For Each oService In cServices
For Each sTargetSvc In aTargetSvcs
If LCase(oService.Name) = LCase(sTargetSvc) Then
If oService.State <> "Stopped" Then
oService.StopService()
Wscript.Echo oService.State
End If
End If
Next
Next
I am just testing it out with mysql and Apache2.4 services, but when this works, it will be deployed with a group policy to temporarily stop some AV services that are interfering with a domain modifier script.

The issue is likely a lack of permission in the context of the running script.
If you run the script from the command line make sure to start it through an Elevated Command Prompt, in modern Windows Operating Systems an elevated Command Prompt is denoted by the prefix Administrator: in the Window Title.
If you run the script from a Shortcut link make sure to specify Run As Administrator in the Advanced Properties screen.

Related

How to close/terminate/kill an instance of a application with VBS? [duplicate]

This question already has answers here:
How to terminate process using VBScript
(2 answers)
Closed 4 years ago.
How to close/terminate/kill an instance of a application with VBS?
I've tried the following code, suggested on several posts, and it didn´t work.
Set x = GetObject(,"xxx.Application")
x.quit
I think I used WMI at one point, and that worked OK - provided the script runs with the access rights required to kill the processes in question (in other words admin rights for system processes, user rights for user context processes - I suppose there could be NT Privileges / NT Rights (system wide privileges) and custom ACL permission settings (access control list - attached to objects) involved as well - the configuration of which might vary from site to site):
Note: the below script will kill all Notepad.exe processes! (unless access is denied)
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'Notepad.exe'")
For Each objProcess in colProcessList
objProcess.Terminate()
Next
Some Links:
Close an application using VBScript (several other options)
Kill a process which says “Access denied” (auperuser - Terminate Process ACL)
Unkillable Processes

Restart a vbs script if it crashes

I'm trying to make a vb script that will restart another vb script if it crashes.
I have searched, and searched but all I get is how to restart a program and since a vb script is a background process it doesn't work when you search in Win32_Process.
Here is my code
set Service = GetObject ("winmgmts:")
set Shell = WScript.CreateObject("WScript.Shell")
sEXEName = "Test_To_Block.vbs"
while true
bRunning = false
for each Process in Service.InstancesOf ("Win32_Process")
if Process.Name = sEXEName then
bRunning=true
msgbox("I am active")
End If
next
if bRunning=False then
msgbox("I am not active.")
Shell.Run sEXEName
end if
WScript.Sleep(100)
wend
The problem is that it never see's the file running and just opens hundreds of "Test_To_Stop.vbs"'s which resolves in me having to restart the computer.
In my opinion what should be changed is where the code is looking for.
for each Process in Service.InstancesOf ("Win32_Process")
Instead of looking in "Win32_Process" you need to look in wherever background process' run.
I am new to coding so sorry if this is a simple question.
Thank you in advance.
Regards,
A Viper
The below code restarts itself via WshShell.Exec() method and trace state of the running script via .Status property of returned object:
If Not WScript.Arguments.Named.Exists("task") Then
Do
With CreateObject("WScript.Shell").Exec("""" & WScript.FullName & """ """ & WScript.ScriptFullName & """ ""/task""")
Do While .Status = 0
WScript.Sleep 1
Loop
End With
Loop
End If
MsgBox "This script will be restarted immediately after termination"
Another way is to use .Run() method with third parameter set to True to wait until launched process terminated:
If Not WScript.Arguments.Named.Exists("task") Then
Do
CreateObject("WScript.Shell").Run """" & WScript.FullName & """ """ & WScript.ScriptFullName & """ ""/task""", 1, True
Loop
End If
MsgBox "This script will be restarted immediately after termination"
Or even simplier:
If Not WScript.Arguments.Named.Exists("task") Then
Do
CreateObject("WScript.Shell").Run """" & WScript.ScriptFullName & """ ""/task""", 1, True
Loop
End If
MsgBox "This script will be restarted immediately after termination"
Probably because the name of the running process is 'wscript.exe' and not 'Test_To_Block.vbs'. You may be able to use the hack mentioned on this page to change the name of the process:
If you're running the scripts locally and running some regular scripts, one
common hack is just to copy and rename wscript.exe to a particular name,
such as "MyScript1.exe". Then run the script with a shortcut as
"...\MyScript1.exe MyScript1.vbs". Then the process will show up as
MyScript1.exe.
Then you can use sEXEName = "MyScript1.exe"
Note: instead of using Shell.run sExeName use Shell.run "Test_To_Block.vbs"

How to detect after system boot if the service is running, if running then start my apps?

In VBScript is it possible to query a specific service name if it's started or running? if its running then execute finally my application. So here is how the flow i am trying to prepare:
System is booted
Windows 8.1 Startup script is executed (VBS)
VBScript now wait and keep checking if the service name "NGINX" started or running already.
If RUNNING, then execute notepad.exe.
If not RUNNING, then start the service "NGINX" and make sure its now "RUNNING". if now "RUNNING" then finally execute notepad.exe.
Is this possible with VBScript?
Example: this line 6 should be only executed if the service NGINX is running otherwise it should never execute that.
Option Explicit
Dim ws
set ws = CreateObject("wscript.shell")
Dim a
a = "C:\Program Files (x86)\abcd\kiosk.jar"
ws.run "java.exe -cp " & chr(34) & a & chr(34) & " kiosk", 0, False
If you want nginx automatically started after system boot you should install it as a service. You can use a WMI query against the Win32_Service class to check if a service is running, and also start it in case it isn't:
Set wmi = GetObject("winmgmts.//./root/cimv2")
qry = "SELECT * FROM Win32_Service WHERE Name = 'nginx' AND State <> 'Running'"
For Each svc In wmi.ExecQuery(qry)
svc.StartService
Next
To just check if the service is running and run some other program if it is you could do something like this:
isRunning = False
qry = "SELECT * FROM Win32_Service WHERE Name = 'nginx' AND State = 'Running'"
For Each svc In wmi.ExecQuery(qry)
isRunning = True
Next
If isRunning Then
CreateObject("WScript.Shell").Run "notepad.exe", 0
End If
No need to install it as a service. Use a scheduled task to launch it at start up, login, or whatever.
I like the WMI method and that would be what I'd want but you could also execute Net Start, read each line of output, then use If Instr to check for your service name. If it comes back True then your service is started. If not, then it hasn't. Nice thing is that you'd already have your connection created to your Wscript.shell so it would be a simple matter to use Net Start again to start the service.
http://www.codeproject.com/Tips/507798/Differences-between-Run-and-Exec-VBScript

How to close Outlook with VBScript when run from Task Scheduler

I have searched the Stack Overflow site for questions related to closing
Outlook. There were a number of hits but none seem to describe what I'm
trying to do.
The problem I'm trying to solve is how to backup the Outlook data base
automatically and unattended. Outlook needs to be closed (if it is
running) before copying the .pst files.
I found a VBScript at (www.howto-outlook.com/howto/closeoutlookscript.htm)
that seems like what I need. But I can't get it to run when initiated from
the Windows Task Scheduler.
I am running on a Windows 8 Sony laptop.
My VBScript should close Outlook prior to doing a backup of the .pst files.
The code is stored in CloseOutlookVerify.vbs.
Below is the offending code from CloseOutlookVerify.vbs:
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'Outlook.exe'")
For Each objProcess in colProcessList
Set objOutlook = CreateObject("Outlook.Application")
' The above line fails with ERR = 70 - Permission denied
objOutlook.Quit
Closed = 1
Next
This script works correctly if I double-click on the .vbs file
from Windows Explorer.
It works correctly if I run it from a DOS Command Prompt window.
It fails with err = 70 when run via the Windows Task Scheduler.
So, what is different about running this script from a command prompt
vs. by the task scheduler? And how can I make it work correctly when run
by the task scheduler?
FYI - I made my living programming in C and Unix shell languages, but this
is my first exposure to VBS in the Windows environment.
Many thanks for any expertise you can provide.
I think it is because impersonationLevel has not been set. Try this:
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strSysName & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'Outlook.exe'")
For Each objProcess in colProcessList
objProcess.Terminate()
Next

mstsc Remote Desktop questions

currently, to improve some inefficiencies on a daily process, I am trying to write a c# Winform app that will combine a mix of user-input with VBscripts that will expedite a previously all user-input process of looking at an excel file and moving files from VSS to certain folders of certain servers.
I was hoping to get some questions answered, pointed in the right way:
Using command line or other workaround instead of manually,
1) Is it possible to log into a 2003 remote desktop with a Smartcard/pin?
2) Is it possible to run a file/start a process on the remote desktop from a command on your machine?
Thanks for the help and time
I have only experience with the second question.
You can do this with remote scripting or with utilities like SysInternals PsExec http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx
here a vbscript that remotely starts a ipconfig command and redirects it to a textfile
Note that you can't start interactive processes like this, they would start but not show up
Dim sComputer 'computer name
Dim sCmdLine 'command line of the process
Dim sCurDir 'working directory of the process
Dim oProcess 'object representing the Win32_Process class
Dim oMethod 'object representing the Create method
sComputer = "." 'this is the local computer, use a pcname or ip-adress to do it remote
sCmdLine = "cmd /c ipconfig.exe > c:\ipconfig.txt"
Set oProcess = GetObject("winmgmts://" & sComputer & "/root/cimv2:Win32_Process")
Set oMethod = oProcess.Methods_("Create")
Set oInPar = oMethod.inParameters.SpawnInstance_()
oInPar.CommandLine = sCmdLine
oInPar.CurrentDirectory = sCurDir
Set oOutPar = oProcess.ExecMethod_("Create", oInPar)
If oOutPar.ReturnValue = 0 Then
WScript.Echo "Create process method completed successfully"
WScript.Echo "New Process ID is " & oOutPar.ProcessId
Else
WScript.Echo "Create process method failed"
End If

Resources