Search code examples
for-loopcmdescapingdoskey

how to escape findstr /r in a for loop to work in doskey


I have this command

for /F "tokens=2 delims=:" %a in ('ipconfig ^| findstr /R "Default Gateway[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*"') do @ping -t %a

this works fine and extracts my default gateway and pings it

I would like to wrap this into a doskey macro called pig (aka ping gateway), but can not escape the findstr correctly. The doskey looks like this (^^ is needed to escape the pipe)

doskey pig = for /F "tokens=2 delims=:" %a in ('ipconfig ^^| findstr /R "Default Gateway[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*"') do @ping -t %a

With this however the doskey does not even register and findstr generates this output

FINDSTR: Cannot open do
FINDSTR: Cannot open @ping
FINDSTR: Cannot open -t
FINDSTR: Cannot open %a

I found out that escaping the last double quote allows for registering the doskey, but if I call the pig, it just outputs this:

More?

My imagination ends here and the machine just asks me for more...

I would like to have a doskey macro which looks up the gateway and pings it for me


Solution

  • First - It's important where you want to put your definition, on the command line or in a batch file. The syntax for the line will be different

    Second - It's important to see what you get.
    You should look into the defined macro with doskey /macros

    If I use your sample on the command line I get:

    pig=for /F "tokens=2 delims=:" %a in ('ipconfig ^
    

    If I use it in a batch file I get:

    pig=for /F "tokens=2 delims=:" a
    

    For the command line you need to use (Three instead of two carets):

    doskey pig=for /F "tokens=2 delims=:" %a in ('ipconfig ^^^| findstr /R "Default Gateway[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*"') do @ping -t %a
    

    Inside a batch file use (The percent signs has to be doubled, too):

    doskey pig=for /F "tokens=2 delims=:" %%a in ('ipconfig ^^^| findstr /R "Default Gateway[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*"') do @ping -t %%a