Thursday, February 15, 2007

Piping the output to a variable in cmd

Some time back I had written that in Batch Files on XP there is no way to assign a variable to the output of some program/batch file, I was incorrect...there is a very convoluted way of doing it using FOR.
Let's say we want to get the names of all services hosted by svchost which has a memory usage of more than some MB:

FOR /F "tokens=*" %i IN ('tasklist /nh /FI "Memusage ge 10000"^|gawk "/svchost.exe/ {print $2}"') DO @echo %i| tasklist /nh /SVC /FI "PID eq %i"

The pipe needs to be escaped by ^; tokens=* means get the entire line and gawk is from unxutils. Before you start thinking how cool this particular example is or how dumb I am, you might want to know that this could have been achieved by just using one command (the example was just to show that you can pipe an output to a variable):

tasklist /SVC /FI "Memusage ge 10000"

2 comments:

  1. Your script as it is doesn't work.

    You have to use double percent signs to make it work.

    %i -> %%i

    ReplyDelete
  2. that's right, you need %% for variables in a bat file...I had written that example directly on command prompt (which just needs a single %).

    ReplyDelete