2

I am trying to write a batch script that saves the result of a command in a variable. so I can use it later.

For example I am tryin to run this on the script: sc queryex "Service" |find /i "pid"

but I want to save this result in a variable.

set PIDRS=sc queryex "Themes" |find /i "pid"
ECHO "%PIDRS%

Any Ideas?

GMB
  • 337
  • 2
  • 6
  • 21
Jorococo
  • 23
  • 5

1 Answers1

2
for /f "tokens=* delims=" %%# in ('sc queryex "Themes" ^|find /i "pid"') do set "PIDRS=%%#"
echo %PIDRS%

This will set the entire line to PIDRS

here's how to get only the pid:

@echo off

set "rspid="
for /f "skip=9 tokens=2 delims=:" %%# in ('sc queryex "Themes"') do (
  if not defined rspid set /a rspid=%%#
)

the second does not use additional FIND which in theory should make it faster.

npocmaka
  • 55,367
  • 18
  • 148
  • 187
  • 3
    `skip=9` fails for a stopped service, leads to `Missing operand` error. I'd use (from command line) `for /F "tokens=1* delims=: " %# in ('sc queryex "Themes"') do @if /I "%#"=="PID" set /A "rspid=%$"` – JosefZ Oct 19 '15 at 16:57
  • @eranotzap it will be assigned to variable `rspid`.You can get its value with `%rspid%` – npocmaka Apr 26 '16 at 07:21