1

Im using the sc command to query the services running on machines and was using code similar to:

      sc \\"server_name" query | find "SERVICE_NAME" > servicelist2.txt

so basically all the server names are listed in this one notepad file. there are 100+ of them. it is too hard to manually put each name in and write 100+ lines of code. is there a way i can use batch itself to direct to the notepad file and iterate through all the server names written in it and then put them back into the "sc" command?

EDIT: Am on windows btw if it wasnt obvious. Using batch scripts for the above.

Jav_Rock
  • 22,059
  • 20
  • 123
  • 164
Gutsygibbon
  • 703
  • 3
  • 8
  • 12

3 Answers3

2

Assuming you have a file named servers.list in the same directory, you can use this:

for /f %%a in (%~d0%~p0servers.list) do (
  ECHO %%a > servicelist2.txt
  sc \\%%a query | find "SERVICE_NAME" > servicelist2.txt
)
LittleBobbyTables - Au Revoir
  • 32,008
  • 25
  • 109
  • 114
  • what is the first line in the do part of the for loop? What is the function of that ECHO? like what does it output and where? – Gutsygibbon Sep 06 '12 at 18:43
  • @Gutsygibbon - oh, I added that as extra information. That writes the server name currently being queried to the servicelist2.txt file, before writing out the results of `SC QUERY`. Otherwise, you won't know what the results of each `SC QUERY` belong to. – LittleBobbyTables - Au Revoir Sep 06 '12 at 18:45
  • Oh ok. lol. One more question, what is the gibberish in the brace brackets of the for loop? I understand the "for /f %%a in" part but the "(%~d0%~p0servers.list)" part is confusing to me. – Gutsygibbon Sep 06 '12 at 18:49
  • See: http://stackoverflow.com/questions/112055/what-does-d0-mean-in-a-windows-batch-file. `~d` is the current drive, and `~p` is the current path. Basically it allows the batch file to find the **servers.list** file in the same directory as the executing batch file. – LittleBobbyTables - Au Revoir Sep 06 '12 at 18:55
  • OH cool. thanks man. I started learning batch yesterday and my boss already wanted me to make a script. Thanks again! – Gutsygibbon Sep 06 '12 at 18:55
1

you can do this with for /f :

OR /F "usebackq tokens=*" %%G IN ("C:\My Documents\servers.txt") DO (
 sc \\%%G query | find "SERVICE_NAME" > servicelist2.txt
)
npocmaka
  • 55,367
  • 18
  • 148
  • 187
0
@echo off
echo Starting to list query services...
for /f %%i in (servieslist2.txt) do sc query %%i > output.txt
echo Finished query services...

The above will loop through each of the 100 service names specified in serviceslist2.txt and output it to a file called output.txt in the same directory as the batch file

m8L
  • 119
  • 4
  • 9
  • ...and overwrite output.txt, so only the last run will get logged. Using `>>` instead of `>` will solve this problem. – Stephan Oct 16 '13 at 16:50