管道運算符(|
)將一個命令的輸出(默認為STDOUT
)引導到另一個命令的輸入(默認為STDIN
)。 例如,以下命令將目錄C:\
的內容進行排序。
dir C:\ | sort
在這個例子中,兩個命令同時啟動,但是sort
命令暫停,直到它接收到dir
命令的輸出。 sort
命令使用dir
命令的輸出作為輸入,然後將其輸出發送到句柄1
(即STDOUT
)。
以下是pipe
命令的另一個示例。 在這個例子中,檔C:\new.txt
的內容通過管道篩檢程式發送到sort
命令。
@echo off
TYPE C:\new.txt | sort
將命令與重定向操作符組合在一起
通常,管道操作符與重定向操作符一起使用,以便在處理管道命令時提供有用的功能。
例如,下麵的命令將首先獲取C:\
中定義的所有檔,然後使用pipe
命令將查找所有帶.txt
擴展名的檔。 然後它將獲取這個輸出並將其輸出到檔AllText.txt
中。
dir C:\ | find "txt" > AllText.txt
使用多個管道命令
要在同一命令中使用多個篩檢程式,請使用管道(|
)分隔篩檢程式。 例如,以下命令搜索驅動器C:\
上的每個目錄,找到包含字串“Log”
的檔案名,然後將它們一次顯示在一個“命令提示符”窗口中 -
dir c:\ /s /b | find "TXT" | more
以下是一些如何使用管道篩檢程式的例子。
例子
以下示例使用tasklist
命令發送所有正在運行的任務的列表,並將輸出發送到find
命令。 然後,find
命令將查找所有類型為QQ
的進程,並將其顯示在命令提示符中。
tasklist | find "QQ"
以下是一個示例輸出 -
C:\Users\Administrator>tasklist | find "QQ"
QQProtect.exe 5672 Services 0 14,136 K
QQ.exe 11672 Console 1 164,156 K
QQExternal.exe 8428 Console 1 32,484 K
以下示例使用tasklist
命令發送所有正在運行的任務的列表,並將輸出發送到more
命令。 然後,more
命令將一次顯示一頁運行任務的列表。
tasklist | more
執行上面示例代碼,得到以下結果 -
映像名稱 PID 會話名 會話# 記憶體使用
========================= ======== ================ =========== ============
System Idle Process 0 Services 0 8 K
System 4 Services 0 136 K
smss.exe 396 Services 0 852 K
csrss.exe 568 Services 0 4,532 K
wininit.exe 656 Services 0 5,328 K
csrss.exe 668 Console 1 4,884 K
winlogon.exe 764 Console 1 7,724 K
services.exe 884 Services 0 8,284 K
lsass.exe 892 Services 0 13,156 K
fontdrvhost.exe 1000 Services 0 3,776 K
fontdrvhost.exe 1008 Console 1 24,784 K
svchost.exe 412 Services 0 3,496 K
svchost.exe 528 Services 0 22,596 K
WUDFHost.exe 880 Services 0 6,132 K
svchost.exe 832 Services 0 11,216 K
svchost.exe 1036 Services 0 8,152 K
dwm.exe 1124 Console 1 44,432 K
-- More --
以下示例使用tasklist
命令發送所有正在運行的任務的列表,並將輸出發送到find
命令。 然後,find
命令將查找所有類型為chrome
的進程,然後使用重定向命令將內容發送到檔tasklist.txt
。
tasklist | find "chrome" > tasklist.txt
如果打開檔tasklist.txt
,就會得到如下的輸出結果 -
chrome.exe 11416 Console 1 164,340 K
chrome.exe 4564 Console 1 10,108 K
chrome.exe 9824 Console 1 10,312 K
chrome.exe 11984 Console 1 86,592 K
chrome.exe 12080 Console 1 23,272 K
chrome.exe 11360 Console 1 139,212 K
chrome.exe 9404 Console 1 108,488 K
chrome.exe 1240 Console 1 74,468 K
chrome.exe 10280 Console 1 119,784 K