user2800660
user2800660

Reputation: 11

Include pipe and redirect inside a for loop

How do I use pipe or redirect inside the cmd for loop?

My sample script is (objective is to see if a series of specific programs / services are running:

for  %%m in ( **{list of individual program names}** ) do (
tasklist /FI "IMAGENAME eq %%m" /NH   ^| find /i "%%m"  
if "%errorlevel%" EQU "1" set /a err_count=%err_count%+1
echo checking tasklist item %%m , count is %err_count%
)

I need to pipe through find, or the tasklist will always complete without error, even if the program isn't running.

I've tried every variation I can think of to escape | and > in the loop, and nothing so far has worked.

The /f delimiters option only works if the command is inside the parentheses for line 1. I want the command inside the loop.

Upvotes: 0

Views: 299

Answers (3)

tallblondandtan
tallblondandtan

Reputation: 31

you must only escape pipe signs, though don't ask me why.

Upvotes: 1

foxidrive
foxidrive

Reputation: 41234

The delayed expansion is a common way to use a variable within a loop, with the !variable! syntax.

A pipe is a normal character within a loop and doesn't need to be escaped.

@echo off
setlocal enabledelayedexpansion
for  %%m in ( **{list of individual program names}** ) do (
tasklist /FI "IMAGENAME eq %%m" /NH    | find /i "%%m"  
if errorlevel 1 set /a err_count+=1
echo checking tasklist item %%m , count is !err_count!
)

Upvotes: 0

cure
cure

Reputation: 2688

for /f %%i in ('dir /b /s *_log.xml ^| find "abc" /i /v') do type "%%~i" >> main_log.xml

escape |'s don't escape >'s. this is because you are ending a command with a non-escaped pipe. whereas you are simply telling the operating system to change the meanings of the program's STDIN and STDOUT with > < >> and <<. also use % not %% at command-line

Upvotes: 0

Related Questions