如何判斷批次檔是否是從命令視窗執行的?

如何判斷批次檔是否是從命令視窗執行的?

我有一個批次文件,我希望能夠透過在 Windows 資源管理器中雙擊該文件來運行該文件。完成後,我想以暫停結束,這樣視窗就不會立即關閉。

但如果批次檔是從命令外殼運行的,我不希望以暫停結束。

有沒有辦法在批次檔中判斷它是在 Windows 資源管理器產生的命令列中運行,還是在現有命令 shell 中運行?

Bash 提供了特殊的 $- 環境變數。

cmd.exe有類似的東西嗎?

答案1

這不是一個確切的解決方案,但您可以建立 cmd 檔案的捷徑並向目標新增命令列參數。當您需要從資源管理器執行 cmd 時,您必須啟動她的捷徑,而不是 cmd 檔案。在您的 cmd 檔案中,您將測試 %1 參數以確定它是從捷徑(從資源管理器)啟動還是從命令提示字元啟動。

答案2

我在 Windows 10 上嘗試了 Gene 的建議:

if /I Not "%CMDCMDLINE:"=%" == "%COMSPEC% " Pause

但這對我不起作用。然而,當我刪除 %COMSPEC% 末尾的空格時,它確實起作用了:

if /I Not "%CMDCMDLINE:"=%" == "%COMSPEC%" Pause

我沒有資格只對原始帖子發表評論,但更希望有人將其添加到吉恩的答案中並投票給他(因為他為我提供了解決問題的基礎)。

答案3

我在這裡發布了類似問題的解決方案:886848/如何製作 Windows 批次檔雙擊時暫停

該解決方案應該適合您,但它比您可能需要的複雜一些。

我在下面發布了它的簡化版本,該版本更簡單並且應該適合您。

您可以在上面鏈接的解決方案中閱讀有關它的更多信息,但它的基礎知識是它使用環境變量:%cmdcmdline%確定批處理文件是否從命令窗口運行。

它之所以有效,是因為變數的內容%cmdcmdline%根據批次檔的啟動方式而有所不同:1) 透過點選批次檔或捷徑,例如從Windows 資源管理器或桌面上,或2) 從命令中執行批次檔提示視窗。

所以,你可以像這樣使用它:

在批次檔退出時,您會新增一些如下程式碼:

set newcmdcmdline=%cmdcmdline:"=-%
echo %newcmdcmdline% | find /i "cmd /c --%~dpf0%-"
set "result=%errorlevel%"

rem if %result% EQU 0 
rem     this batch file was executed by clicking a batch file 
rem     or a shortcut to a batch file, typically from Windows Explorer 
rem     or the Desktop, or the "Start Menu" ...

rem if %result% NEQ 0 
rem     this batch file was executed from within a Command Prompt

rem if executed from within a Command Prompt: 
rem     go exit the batch script immediately, without pausing. 
rem     since this batch file was executed from within a 
rem     Command Prompt, the command window will remain open. 
rem     You can use either of these to exit the batch file:
rem          goto :EOF
rem          exit /b

if %result% NEQ 0 goto :EOF

rem at this point, we know this batch file was executed by clicking ..., 
rem     NOT from within a Command Prompt. 

rem leave the command prompt window open to allow the user time to 
rem    view the messages on the screen before exiting. Use any of 
rem    these to pause and or interact with the user before exiting: 
rem        pause
rem        echo Message... &pause
rem        set /p "d=Message..."
rem        choice [Options...]
rem            (choice /? Displays help message for the Choice command)
rem        timeout /T wait-time [Options...]
rem            (timeout /? Displays help message for the Timeout command)

timeout /t 10
goto :EOF

答案4

在所有情況下,給出的答案對我來說都不是可靠的,特別是當透過 Windows 捷徑從桌面或從第 3 方檔案管理器(例如 FreeCommander)啟動時

對我有用的是:

if "%CMDCMDLINE:"=%" == "%COMSPEC%" (
  REM started via windows explorer
) else if "%CMDCMDLINE%" == "cmd.exe" (
  REM started via file manager (e.g. FreeCommander)
) else if "%CMDCMDLINE:"=%" == "%COMSPEC% /c %~dpf0 " (
  REM started in command window
) else (
  REM started from other batch file
)

相關內容