Home > Mobile >  Pipe symbol | unexpected in FOR /F loop
Pipe symbol | unexpected in FOR /F loop

Time:01-11

FOR /F "tokens=3 delims= " %i IN (query session | FINDSTR /i "console") DO set "ID=%i"

I am getting an error | was unexpected at this time.

CodePudding user response:

Two very simple mistakes to avoid.

First by reading For /? use 'single quotes' for commands.

Secondly ^escape the |

FOR /F "tokens=3 delims= " %i IN ('query session ^| FINDSTR  /i "console"') DO set "ID=%i"

Reminder as mentioned by @aschipfl in comment use doubled %% for both of your i's in a batch file or file.cmd

enter image description here

CodePudding user response:

You should always read the usage information for a command utility before you use it. Had you done so, you would have noted that as you are specifically trying to isolate a line with the session name console, you could have used query session console instead of the less robust query session | FINDSTR /i "console". Of course, using the more appropriate command would mean that you do not have any issue with a horizontal bar, (pipe).

If you wanted, you could also skip the first, (header), line, and if you are certain, that your ID will always be the third whitespace separated token, you could then use:

From the Command Prompt, ():

For /F "Skip=1 Tokens=3" %G In ('%SystemRoot%\System32\query.exe Session Console 2^>NUL') Do @Set "ID=%G"

Or from a batch file, ():

@For /F "Skip=1 Tokens=3" %%G In ('%SystemRoot%\System32\query.exe Session Console 2^>NUL') Do @Set "ID=%%G"
  •  Tags:  
  • Related