Question : How to assign Command output to a variable in batch

sc \\mycomputer01 query type= service |find "SERVICE_NAME"|find /c"squid"

I would like to assign the output of the above command to a variable in windows batch.


I have something like this but it does not just work. Please help.

for /F "tokens=* " %%a in ('sc \\mycomputer01 query type= service ^| find "SERVICE_NAME" ^| find /c"squid"') do echo %%a

Answer : How to assign Command output to a variable in batch

Ah, since the code you showed earlier is actually inside a FOR loop, then you will need to use Delayed Expansion of environment variables.  Change as follows:

@echo Off
setlocal EnableDelayedExpansion
SET MyVar=
for /F %%p in (hosts.txt) do (
  for /F "tokens=*" %%a in ('sc \\%%p.mynet.com query type^= service ^| find "SERVICE_NAME" ^| find /c"squid"') do SET MyVar=%%a
  echo !MyVar!
)

Further reading here:

http://ss64.com/nt/setlocal.html
http://blogs.msdn.com/b/oldnewthing/archive/2006/08/23/714650.aspx

~bp
Random Solutions  
 
programming4us programming4us