0

I just want to know how we can parse the batch command output. The following one is the small example where Iam trying to get the service name.

C:\Users\pande\Desktop>sc qdescription "test"
[SC] QueryServiceConfig2 SUCCESS

SERVICE_NAME: test
DESCRIPTION:  C:\Program Files (x86)\TEST\small.exe /service

Here the question is , from the above result I want to hold the below part as a batch file variable.

C:\Program Files (x86)\TEST\

By goggling we can achieve this by for /f, but really don't know how I can get it.

Can anyone please help me to achieve this.

Thanks In Advance.

1 Answer 1

1
@ECHO OFF
SETLOCAL
SET "DESC="
FOR /f "tokens=1*delims=: " %%a IN ('sc qdescription "bonjour service" ') DO (
 IF "%%a"=="DESCRIPTION" SET "desc=%%b"
)
ECHO DESC=%DESC%

:: Setting DESC to the string expected - then ECHOing to prove

SET "DESC=C:\Program Files (x86)\TEST\small.exe /service"
ECHO DESC=%DESC%

:: Now remove part past '/' and select drive/path from assumed filename

FOR /f "tokens=1delims=/" %%a IN ("%desc%") DO SET "desc=%%~dpa"
ECHO DESC=%DESC%

:: Now remove terminal "\"

SET "desc=%desc:~0,-1%"
ECHO DESC=%DESC%

:: Extension - to remove the last "leaf" directoryname
::
FOR /f "delims=" %%a IN ("%desc%") DO SET "desc=%%~dpa"
ECHO DESC=%DESC%

:: Now remove new terminal "\"

SET "desc=%desc:~0,-1%"
ECHO DESC=%DESC%

GOTO :EOF

You'd need to save this text in a file named whateveryoulike.bat then run it as whateveryoulike from the command-prompt.

I used an installed service on my machine since I don't have access to yours. You would need to substitute your servicename in place of bonjour service above.

I then set desc to the value you show you are getting, and then how to process it down to the portion you require.


Modified to remove the last directoryname leaf.

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, thanks a lot for your valuable reply.This is what Am looking for.
Hi Magoo, small doubt that if I want to get only "C:\Program Files (x86)" what should I do.Please reply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.