2015-12-07 76 views
0

我可以在命令提示符 tasklist /fi "imagename ne siebde*" /fi "imagename eq sieb*" /svc | find "gtwyns"下得到正確的輸出結果。批量轉義字符使用^

但是,如果我想在批處理文件中使用這個條件,我必須使用下面的命令來做到這一點。

for /f "tokens=2 delims= " %%a in ('tasklist /fi "imagename ne siebde*" /fi "imagename eq sieb*" /svc ^| find "gtwyns") 

我需要理解^字符的功能,它是如何工作的?

我也想知道當它在批處理腳本中使用管道時是否會打開一個新的cmd?

+0

你可以自己回答兩個問題。你已經經歷過在''''''for'命令前面需要'^'。原因是在通過執行之前逃避'|'字符並防止在蝙蝠中被解釋。當你執行它時,cmd窗口是否打開? –

+1

@PA管道沒有打開一個新窗口,但它確實啓動了兩個新的cmd.exe實例(每個管道一端) – jeb

+0

不,它不會打開一個新窗口..如果我詳細說明.. 在一個批處理文件中,如果我有以下代碼,我可以執行下面的命令而不使用^符號.. sc \\ EDCBSCSR4DE-001查詢siebsrvr_VIVO_SES_VIVO_SRVR |找到 「停止」 如果%ERRORLEVEL%= = 0( 轉到:停止 )其他( 轉到:停止 ) – learntolive

回答

2

閱讀FOR /F: loop command against the results of another command語法:

FOR /F ["options"] %%parameter IN ('command_to_process') DO command 
… 
command_to_process : The output of the 'command_to_process' is passed 
        into the FOR parameter. 

...的command_to_process幾乎可以是任何內部或外部 命令。

幾乎任何內部或外部命令(但唯一的命令)。

現在,讀redirection語法:

commandA | commandB管從commandA輸出到 commandB

例如,在錯誤for /F "delims=" %%a in ('dir /B | sort /R') do echo %%~a
與轉義|管:

  • commandA的計算結果爲for /F "delims=" %%a in ('dir /B
  • commandB評估爲sort /R') do echo %%~a雖然單獨dir /B | sort /R是正確的命令。

因此,我們需要escape(全部)&|<>重定向字符和(有時)"雙引號如下(兩種方式是等價的解析dir /B "*.vbs" 2>NUL | sort /R命令):

for /F "delims=" %%a in (' dir /B "*.vbs" 2^>NUL ^| sort /R ') do echo %%~a 
for /F "delims=" %%a in ('"dir /B ""*.vbs"" 2>NUL | sort /R"') do echo %%~a 

因此,接下來的兩個迴路應該以相同的方式工作:

for /f "tokens=2 delims= " %%a in (' 
    tasklist /fi "imagename ne siebde*" /fi "imagename eq sieb*" /svc ^| find "gtwyns" 
    ') do echo set pid_ns=%%a 

for /f "tokens=2 delims= " %%a in (' 
    "tasklist /fi ""imagename ne siebde*"" /fi ""imagename eq sieb*"" /svc | find ""gtwyns""" 
') do echo set pid_ns=%%a 
+0

感謝您的澄清 – learntolive