user3408678
user3408678

Reputation: 155

Batch for loop delimeters

Since Windows cmd syntax is ridiculously and unnecessarily complex and difficult to read, I'm having a hard time figuring out the right way to type this. Basically I'm just trying to create a for loop that runs:

sc query | findstr SERVICE_NAME

Then takes the services from the output and runs:

sc sdshow "SERVICE_NAME"

Here's what I've been trying:

for /f "tokens=2 delims= " %a IN ("sc query | findstr SERVICE_NAME") DO sc sdshow %a

But apparently the delimeter is selecting the 2nd token in the command that I type, not the output. I thought it worked similar to: "cut -d " " -f2," but apparently not. Is there even a way to do this in the terrible monstrosity that is Windows cmd syntax?

Upvotes: 1

Views: 89

Answers (1)

SomethingDark
SomethingDark

Reputation: 14305

For what it's worth, you were really close. In batch, you manipulate the output of a command with a for loop using single quotes ('). Also, you need to escape the pipe inside of the command with a ^.

Inside of batch files, you need to call the for loop variables with two % signs (although you only need one if you're typing it on the command line).

for /f "tokens=2 delims= " %%a in ('sc query ^| findstr "SERVICE_NAME"') do sc sdshow %%a

Upvotes: 2

Related Questions