Find a service with Partial name VBS - vbscript

We have a service that runs with different names on different machines like
Bomgar-scadsadccd, Bomgarsdscchfn, Bomgarscnkfkdk
So, here we need to write a VB script that will find this service with partial name "Bomgar"
and check it's status like
1) Not present, then should install from a shared folder like "start \10.216.16.245\Bomgar.exe"
2) Installed but not running, then start the service.
3) Installed and running then quit.
How can we achieve this?
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colRunningServices = objWMIService.ExecQuery("Select * from Win32_Service where Name='bomgar*'")
nItems = colRunningServices.Count
If nItems > 0 Then
For Each objItem in colRunningServices
If objItem.State = "Stopped" Then
objItem.startservice
ElseIf objItem.State = "Running" Then
exit
End If
Next
Else
start \\10.18.23.245\Shared\Bomgar.exe
End If

You can use the like keyword and % wildcards in your WQL statement to find any services containing certain text. For example:
Set colRunningServices = objWMIService.ExecQuery("Select * from Win32_Service where Name like '%bomgar%'")
And instead of start, you'll need to use something like the Run command of the WshShell object to launch your EXE:
With CreateObject("WScript.Shell")
.Run "\\10.18.23.245\Shared\Bomgar.exe"
End With

Related

How to get running application name by vbscript

I would like to get the name list of running application by vbscript and kill the application by its main window title. Those applications should be listed on Task Manager -> Applications tab
Like this:
After searching from web, I found vbscript like this:
'FUNCTION
Function ListProcessRunning()
'This function can report names from
'TaskManager -> Processes
sComputerName = "."
Set objWMIService = GetObject("winmgmts:\\" & sComputerName & "\root\cimv2")
sQuery = "SELECT * FROM Win32_Process"
Set objItems = objWMIService.ExecQuery(sQuery)
'iterate all item(s)
For Each objItem In objItems
WScript.Echo objItem.Name
Next
End Function
This vbscript list all process names which are under Task Manager -> Processes tag like this:
Which is not what I want.
I also found this:
'FUNCTION
Function ListApplicationRunning()
'This function can report names from
'TaskManager -> Application
Set Word = CreateObject("word.application")
For Each x In Word.Tasks
WScript.Echo x.Name
Next
Word.Quit
Set Word = Nothing
End Function
Which really give me what I want but the problem is the server I am going to run this script has no Word so no word.application for vbscript and I am not able to install one for it.
My question is how to get the application name and kill the application by that name? I am not sure is it possible to do with vbscript only, may be a combination of vbscript and cmd is also okay.
In vbscript we can do something like that just give a try with it :
Option Explicit
Call KillProcessbyName("common-api.jar")
'*********************************************************************************
Sub KillProcessbyName(FileName)
On Error Resume Next
Dim WshShell,strComputer,objWMIService,colProcesses,objProcess
Set WshShell = CreateObject("Wscript.Shell")
strComputer = "."
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery("SELECT * FROM Win32_Process")
For Each objProcess in colProcesses
If InStr(objProcess.CommandLine,FileName) > 0 Then
If Err <> 0 Then
MsgBox Err.Description,VbCritical,Err.Description
Else
objProcess.Terminate(0)
End if
End If
Next
End Sub
'**********************************************************************************
FOR /F "usebackq tokens=1-2" %i IN (`tasklist ^|findstr /b "notepad"`) DO taskkill /PID %j

Return volume name in Do loop

I'm trying to create a script for HP UFT to automatically create/mount/unmount VHDs as needed. The problem is that diskpart takes quite a while to create, mount, format and label the VHD. I need a method to pause the script while the VHD is being created/mounted, after which it will continue on with the script.
The variable uftDrive is currently returning a drive letter, not a volume name, so the loop just runs indefinitely. Any thoughts as to how to pass the volume names as a variable? The VHD script is automatically assigning the first-available drive letter to the drive, as we have multiple machines that UFT will be run on, and they don't have identical network drive mappings, forcing us to dynamically detect the drive by volume name.
'===========================================================================
'This will check to see if the Virtual Hard Disk (VHD) exists, and if not,
'create it
'===========================================================================
Dim makevhdExists, vhdExists
Set makevhdExists = CreateObject("Scripting.FileSystemObject")
Set vhdExists = CreateObject("Scripting.FileSystemObject")
If Not makevhdExists.FileExists("c:\UFT\mountVHD.bat") Then
makevhdExists.CopyFile "\\companyADfolders\Users\UFT\VHD\*.*", "c:\UFT\"
End If
If Not makevhdExists.FileExists("c:\UFT\unmountVHD.bat") Then
wait 2
ElseIf Not vhdExists.FileExists("C:\UFT\UFT.vhd") Then
SystemUtil.Run "cmd","/c""C:\UFT\createVHD.bat"""
End If
Dim uftExists, uftDrive
uftExists = "False"
Do
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery _
("Select * From Win32_LogicalDisk Where VolumeName = 'UFT'")
For Each objItem in colItems
uftDrive = objItem.Name 'This is currently returning a drive letter,
'not a volume name
If uftDrive.Name = "UFT" Then
uftExists = "True"**
End If
Next
Loop Until uftExists = "True"
For the wait part
WScript.Sleep 5000
where the value indicated is milliseconds
For the second part, maybe i'm missing something, so, instead of an answer I have one silly question:
If you query wmi for win32_logicaldisk instances where their VolumeName is UFT, WHY your if command checks the Name property instead of the VolumeName property?
In any case, you don't need that if. If colItems.Count is greater than 0, there is at least one instance that matches the indicated condition
Something like this should work
Dim uftExists
uftExists = False
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Do
Set colItems = objWMIService.ExecQuery _
("Select * From Win32_LogicalDisk Where VolumeName = 'UFT'")
If colItems.Count > 0 Then
utfExists = True
Else
Sleep 500
End If
Loop Until uftExists
Changing ObjItem.Name to ObjItem.VolumeName worked!
For Each objItem in colItems
uftDrive = objItem.VolumeName 'This is currently returning a drive letter, not a volume name
If uftDrive = "UFT" Then
uftExists = "True"**
End If
Next
For the first question: To delay the script, you can use this function:
WScript.Sleep 1000
The number is in Milliseconds, so 1000 is 1 second.

Need a VB Script to check if service exist

I want to write a VBS script which will check if specific service is installed/exist or not locally.
If it is not installed/exist, script will display message (any text) and disabled the network interface i.e. NIC.
If service exist and running, NO Action. Just exit.
If service exist but not running, same action, script will display message (any text) and disabled the network interface i.e. NIC.
i have below given code which is displaying a message in case one service is stop but it is not -
Checking if service exist or not
Disabling the NIC
strComputer = "."
Set objWMIService = Getobject("winmgmts:"_
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colRunningServices = onjWMIService.ExecQuery _
("select State from Win32_Service where Name = 'dhcp'")
For Each objService in colRunningServices
If objService.State <> "Running" Then
errReturn = msgbox ("Stopped")
End If
Next
Please help. Thanks in advance.
To know if service is installed, check colRunningServices.Count . It will be 0 if no service match the wmi query.
To disable NIC, use a wmi query SELECT * FROM Win32_NetworkAdapter, iterate de returned collection of NICs, find the one you are interested and use the Disable/Enable method of it. BUT this only will work if OS is Vista or later.
It would look something like this but I cannot test this!
Option Explicit
Const TITLE = "Title"
Const SERVICE = "dhcp"
Dim wmi
Dim svcs,svc
Set wmi = GetObject("winmgmts:\\.\root\cimv2")
Set svcs = wmi.ExecQuery("Select * from Win32_Service where Name = '" & SERVICE & "'")
If svcs.Count = 0 Then
Call MsgBox(SERVICE & " service does not exist",vbCritical,TITLE)
Call disableNIC(wmi)
Else
For Each svc In svcs
If svc.State <> "Running" Then
Call MsgBox(SERVICE & " service is not running",vbCritical,TITLE)
Call disableNIC(wmi)
End If
Next
End If
Set wmi = Nothing
WScript.Quit
Sub disableNIC(ByRef wmi)
Dim nics,nic
Set nics = wmi.ExecQuery("Select * from Win32_NetworkAdapter")
For Each nic In nics
nic.Disable
Next
End Sub
Beware that this disables every NIC. If you want to specify one you'd have to add a where clause in disableNIC. Also I imagine you would have to run this as an administrator.
Seems like a weird thing to want to do though...

Start Service with VBscript

I am trying to have this script take a text file running and stopped services before a reboot and start any services that did not automatically start after the machine starts back up. The script that gets the list of service names, state and startmode and creates a comma separated text file line by line works fine. Here it is for reference (taken from the interwebs, lost the link in my travels. Modified slightly.):
Const ForAppending = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = objFSO.CreateTextFile("service_list.txt", _
ForWriting, True)
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery("Select * from Win32_Service")
For Each objService in colListOfServices
objLogFile.Write objService.Name & ","
objLogFile.Write objService.StartMode & ","
objLogFile.Write objService.State
objLogFile.Writeline
Next
objLogFile.Close
This next bit reads the file line by line, compares the state of all of the services with the state of the services that were recorded before the machine was shut down. If they match, do nothing, if they are different, start the service:
Const ForReading = 1
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objServiceName = objWMIService.get("Win32_Service.Name='" & ServiceName & "'")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("\\some path\service_list.txt",ForReading,True,-2)
Do Until objFile.AtEndOfStream
fLine = Split(objFile.ReadLine,",")
'wscript.echo fLine(2)
if InStr(fLine(2),"Running") then
'wscript.echo "it was running!"
if objServiceName.Started then
'do nothing
else
'Set servicetostart = objWMIService.ExecQuery ("Select " & ServiceName & " from Win32_Service Where Name ='Alerter'")
'servicetostart.StartService()
'Result = objServiceName.StartService
'If 0 <> Result Then
' wscript.echo "Start " & ServiceName & " error:" & Result
'End If
objServiceName.StartService
'wscript.echo Servicename & "could not start with error: " & Result
end if
end if
'wscript.echo objServiceName
Loop
As of right now I am recieving an error whenever it actually tries to start the service. I receive a "Provider Failure code:80041004 Source:SWbemObjectEX". I have been looking through the posts about this error and attempting the fixes suggested. Also, as you can see, I have been trying variations, but I am afraid I am merely guessing.
So to my question, what is causing the "Provider Failure"? I have looked up these information for the Win32_Service Class here:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa394418%28v=vs.85%29.aspx#methods
and looked up the method here:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa393660%28v=vs.85%29.aspx
But have been unable to work out where the I am going wrong.
Thanks,
Joe
on a side note, the service I am testing, ie. making sure the service is starting, creating the text file, then stopping the service and running the "start service" code is Windows Defender. The service name is "WinDefend".
FINAL WORKING CODE:
Const ForReading = 1
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("\\vmware-host\Shared Folders\Documents\Biffduncan\Monthly Server Maintanence\service_list.txt",ForReading,True,-2)
Do Until objFile.AtEndOfStream
fLine = Split(objFile.ReadLine,",")
Set objService = objWMIService.get("Win32_Service.Name='" & fLine(0) & "'")
if InStr(fLine(2),"Running") then
'wscript.echo "it was running!"
if objService.Started then
'do nothing
else
Result = objService.StartService()
if Result <> 0 then
wscript.echo "The service: " & objService.Name & " did not start with error: " & Result
else
wscript.echo "Service " & objService.Name & " started"
end if
end if
end if
Loop
Error code 0x80041004 means that the WMI provider encountered an error after it was already initialized. The error code doesn't say anything about the cause of the error, though, nor does it provide any details. Try running WBEMTest or WMIDiag to track down the error. Also check the eventlog for related errors/warnings. If everything else fails, try rebuilding the WMI repository.
As for your code, the first thing I'd do is strip it down to the bare minimum, to avoid potential error sources:
Set wmi = GetObject("winmgmts://./root/cimv2")
Set svc = wmi.Get("Win32_Service.Name='WinDefend'")
rc = svc.StartService
WScript.Echo rc
Also, I wouldn't recommend writing the service status to a file at some random point in time, and then try starting services according to the contents of that file. There is no guarantee that the start mode hasn't been changed since the file was created, or that the service is even installed anymore.
Whether or not a service should be started is indicated by its StartMode property, so just check those services that are set to Auto. Services set to Manual will be started by the system on demand, so there's no need to launch them just because they were running when you took the snapshot.
qry = "SELECT * FROM Win32_Service WHERE StartMode='Auto'"
For Each svc In wmi.ExecQuery(qry)
If Not svc.Started Then svc.StartService
Next

How can I kill a process, using VBScript, started by a particular user

I have multiple users running attachemate on a Windows 2003 server. I want to kill attachemate.exe started by user_1 without killing attachemate.exe started by user_2.
I want to use VBScript.
You could use this to find out who the process owner is, then once you have that you can use Win32_Process to kill the process by the process ID.
MSDN Win32_Process class details
MSDN Terminating a process with Win32_Process
There is surely a cleaner way to do this, but here's what I came up with. NOTE: This doesn't deal with multiple processes of the same name of course, but I figure you can work that part out with an array to hold them or something like that. :)
strComputer = "."
strOwner = "A111111"
strProcess = "'notepad.exe'"
' Connect to WMI service and Win32_Process filtering by name'
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colProcessbyName = objWMIService.ExecQuery("Select * from Win32_Process Where Name = " _
& strProcess)
' Get the process ID for the process started by the user in question'
For Each objProcess in colProcessbyName
colProperties = objProcess.GetOwner(strUsername,strUserDomain)
if strUsername = strOwner then
strProcessID = objProcess.ProcessId
end if
next
' We have the process ID for the app in question for the user, now we kill it'
Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process where ProcessId =" & strProcessID)
For Each objProcess in colProcess
objProcess.Terminate()
Next
Shell out to pskill from http://sysinternals.com/
Commandline: pskill -u user_1 attachemate.exe

Resources