How to stop a service in cmd only knowing the name of the .exe file? - windows

I need to stop a windows service in a batch file without knowing the name of the service. The only thing I know is that the file running is called SomeServer.exe but the SC command requires the actual name of the service.
Currently I have to scan a config file and perform ugly string operations but I hope there is a smarter way.
Any suggestions?

for /f "tokens=2 delims=," %%a in (
'wmic service get name^,pathname^,state /format:csv ^| findstr /i /r /c:"SomeServer\.exe.*Running$"'
) do sc stop "%%a"
It retrieves the system name, service name, path name and state of the services in csv format. The list is filtered for the required executable name in Running state, splitted using the comma as separator, and the second field (the service name) is used to stop the service

this may be helpfull
http://richarddingwall.name/2009/06/18/windows-equivalents-of-ps-and-kill-commands/
If you’ve ever used Unix, you’ll no doubt be well-aquainted with the
commands ps and kill. On Windows, the graphical Task Manager performs
these roles pretty well, but if you ever find yourself needing to
resort to the command line to kill a process (e.g. for some reason on
the Vista machine I am writing this on Task Manager just sits in the
system tray flashing instead of opening), the Windows equivalents of
ps and kill are tasklist and taskkill:
tasklist /v - equivalent to ps aux
taskkill /f /im ncover* - equivalent to kill -9 ncover*
and there is also pslist http://technet.microsoft.com/en-us/sysinternals/bb896682.aspx
edit:
for services use psservice http://technet.microsoft.com/en-us/sysinternals/bb897542.aspx
or use the method described here (using the registry) https://stackoverflow.com/a/298823/1342402

Related

Wait for a .bat file to close within a windows batch file

I need to create a windows batch file (*.bat) file that only runs its commands if certain processes (and batch files) are NOT running.
I have looked at a solution that works for processes (*.exe) here:
How to wait for a process to terminate to execute another process in batch file
I want to do something very similar, however, there is one difficulty: Batch files show up as "cmd.exe" in the "TASKLIST" command.
I want to check if a specific bat file is running, for example: "C:\mybatch.bat", and if it is, wait until it is closed.
Checking if a specific bat file mybatch.bat is running could be a tougher task than it could look at first sight.
Looking for a particular window title in tasklist /V as well as testing CommandLine property in wmic process where "name='cmd.exe'" get CommandLine might fail under some imaginable circumstance.
1st. Can you
add title ThisIsDistinguishingString command at beginning of the mybatch.bat and
remove all other title commands from mybatch.bat and
ensure that mybatch.bat does not call another batch script(s) containing a title command?
Then check errorlevel returned from find command as follows:
:testMybatch
tasklist /V /FI "imagename eq cmd.exe" | find "ThisIsDistinguishingString" > nul
if errorlevel 1 (
rem echo mybatch.bat batch not found
) else (
echo mybatch.bat is running %date% %time%
timeout /T 10 /NOBREAK >NUL 2>&1
goto :testMybatch
)
2nd. Otherwise, check if wmic Windows Management Instrumentation command output could help
wmic process where "name='cmd.exe'" get /value
Then you could detect mybatch.bat in its output narrowed to
wmic process where "name='cmd.exe'" get CommandLine, ProcessID
Note that wmic could return some Win32_Process class properties, particularly CommandLine, empty if a particular process was launched under another user account or elevated (run as administrator).
Elevated wmic returns all properties in full.
What you say happens by default.
To test, crate a new .bat file (let's say 1.bat) and put in it
calc
mspaint
Save and run it.
Calculator will start. You will notice that Paitbrush will launch only when you have closed calculator.

Kill a windows service using its Service Name

I am looking for a way to kill a windows services using its service name rather than the process name, or PID. The two obvious choices are pskill or taskkill, but I cannot seem to find a way of using either of these methods to kill the service by name.
Is it possible to do it by the service name? If so, is anyone able to provide a quick example?
You can use taskkill to filter by service name and kill the service you're looking for.
taskkill /F /FI "SERVICES eq yourservice"
Do you actually want to KILL the process (e.g. if it is frozen) or do you want to STOP the service?
If you want to kill it stick to SomethingDark's answer (taskkill /F /FI "SERVICES eq yourservice").
If you want to stop it use SC STOP "servicename".
In case you have multiple services with the same image name, using the SERVICES filter may not be sufficient. In this case, you need to use more filters like IMAGENAME, PID, STATUS or more.
See my related answer here
with taskkill loop (be careful with closing system processes) (save winservices.bat and run as admin)
call :winservices "service_name1"
call :winservices "service_name2"
:: funcion winservices
#echo off
goto:eof
:winservices
set winservices=%1
taskkill /f /im "%winservices%" /t
goto:eof
source: https://serverfault.com/questions/1005487/how-to-stop-start-and-delete-a-windows-service-with-a-reference-to-the-service

How to write batch file to retsart services with varying names

I'm trying to write a batch file that will restart a service from a program my company uses called Bomgar that allows our help desk technicians to remote into an employees computer. I know how to write a batch file that restarts services, the problem is that each service has a unique number ID on it (example; bomgar-ps-10000000-10000000) that is completely different machine to machine. Is there a way to restart services whose name falls within a "range"? Say any service whose name contains "bomgar-ps" as an example.
Really not sure how to handle this. The problem we're having is that this service is failing to start up occasionally and when an employee calls with a problem, they aren't tech savvy so a lot of time is wasted trying to guide them into services.msc and manually restarting the service.
This should work also.
#echo off
set "servicename="
for /f "tokens=*" %%a in ('net start ^| find /i "bomgar-ps") do set "servicename=%%a"
if defined servicename net stop "%servicename%"
ping -n 3 localhost >nul
net start "%servicename%"
echo servicename "%servicename%" has attempted to restart
If you are merely guiding someone over the phone to restart the service then this will print the name to the console, in a fairly simple manner (add /i to the find command if bomgar can be mixed case"
net start|find "bomgar"
Try this, I used it to search for the print spooler name and restart it. You should be able to replace spool with boomgar-ps, you may even be able to remove the SERVICE_NAME: part.
#ECHO OFF
>%TEMP%\~sc.log (sc queryex type= service state= all)
for /F "tokens=1,* delims=: " %%I in ('type %TEMP%\~sc.log^|find "SERVICE_NAME: Spool"') do set scname=%%J
ECHO RESTARTING %scname%
sc stop %scname%
sc start %scname%

Attaching the windows debugger in VS2010 from a batch file?

Is it possible to attach the windows debugger in VS2010 to a process from a batch file?
preferably by giving it a process name
Since you presumably already have the process running, you would use vsjitdebugger.exe /p 1234 where 1234 is the PID of the process you want to debug. If you don't know it, you would have to use some other method to figure it out.
If you have the debugging tools for windows available, the tlist.exe utility will yield the process ID for a process name. If that is available, then the following will attach to a given process:
rem Get the process ID
for /f %%f in ('tlist -p %1') do set mypid=%%f
rem attach to it with selected debugger
vsjitDebugger -p %mypid%
Edit If tlist is not available, I think tasklist will work. It's a bit uglier, but the following worked for me (you know ... it works my on my system :) Note too that I edited the command previous example to work in a cmd.exe prompt (I use tcc, which does require as many % signs).
rem Get the process ID
for /f "tokens=2 delims= " %%f in ('tasklist /nh /fi "imagename eq %1"' ) do set mypid=%%f
rem attach to it with selected debugger
vsjitDebugger -p %mypid%
Specifying a /Command switch on devenv.exe 's command-line will make it run a specified command on open. You could specify the Debug.AttachToProcess command. Don't know if you can specify a pid, though, when you execute that command.

Why does batch file FOR fail when iterating over command output?

I have a batch file that uses this idiom (many times) to read a registry value into an environment variable:
FOR /F "tokens=2* delims= " %%A IN ('REG QUERY "HKLM\SOFTWARE\Path\To\Key" /v ValueName') DO SET MyVariable=%%B
(There's a tab character after delims=)
This works fine on thousands of customer's computers. But on one customer's computer (running Windows Server 2003, command extensions enabled),
it fails with 'REG QUERY "HKLM\SOFTWARE\Path\To\Key" /v ValueName' is not recognized as an internal or external command, operable program or batch file.' Running the "reg query" command alone works fine. Reg.exe is present in C:\Windows\System32.
I was able to work around the problem by changing the code to
REG QUERY "HKLM\SOFTWARE\Path\To\Key" /v ValueName > temp.txt
FOR /F "tokens=2* delims= " %%A IN (temp.txt) DO SET MyVariable=%%B
This got the customer up and running, but I would like to understand why the problem occurred so I can avoid it in the future.
Slightly off the primary topic - a more direct way to get a registry value (string or DWORD) into an environment variable would also be useful.
I would check:
The customer's role on the machine - are they an admin?
Where is reg.exe on the box - is there more than one copy of copy of reg.exe in the path?
Is there any locale difference on the customer's machine from the machines where this normally works?
Basically, enumerate everything that differs between this machine and machines where it works as expected. Include service packs, domain membership, etc.
Wow, that is odd.
If the same commands work when split into two lines, then I'd guess it has something to do with the way the command gets run in a subshell in the FOR command.
If you were really dying to figure out why it's dying in this particular case, you could run commands like "SET > envvars.txt" as the FOR command and compare that with the top shell.
Or maybe start off simple and try running the REG command via CMD /C to see if that does anything?
One quick guess here, what's the values of COMSPEC and SHELL ?
I had a similar situation to this. In my case it was a bad value in COMSPEC. I fixed that and the script started working as expected.
The /F switch needs command extensions to be turned on. Usually they are turned on by default, but I'd check that. On XP systems you can turn them on doing something like
cmd /e:on
or checking the registry under
HKCU\Software\Microsoft\Command Processor\EnableExtensions
Dunno about Windows Server.
Doing help for and help cmd could provide some hints as well.

Resources