Search code examples
windowsbatch-filepipeline

Why can't I pipe 'where' output to 'type' in batch?


I'm trying to print the contents of a batch file that exists in my path.

I can find the file with 'where':

> where myscript
C:\scripts\myscript.bat

I can display the contents of the file with 'type':

> type C:\scripts\myscript.bat
echo This is my script. There are many like it, but this one is mine.

However, when I want to be lazy and use a single command:

> where myscript | type
The syntax of the command is incorrect.

Based on some tests I did, it seems 'where' output can't be piped out and 'type' input can't be piped in.

Can anyone explain why this doesn't work in this way?

P.S. I was able to do this in Powershell: Get-Command myscript | Get-Content.


Solution

  • As @Luaan said in the comments, type will only accept the filename as argument and not via its input channel. So piping won't do the trick in your case. You'll have to use another way to give the result of the where command as an argument. Fortunately the for /f can help you process outputs of other commands. To print the file corresponding to the output of the where command you'll have to use this on the command line:

    FOR /F "delims=" %G IN ('where myscript') DO type "%G"
    

    In a batch-file you'll have to use

    @echo off
    FOR /F "delims=" %%G IN ('where myscript') DO type "%%G"