确定批处理脚本已经从线 - 或 - 要暂停或不暂停执行的命令? [英] Determining if the batch script has been executed from the command line -or- To pause or not to pause?

查看:177
本文介绍了确定批处理脚本已经从线 - 或 - 要暂停或不暂停执行的命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个典型的用法:行,我的cmd.exe 脚本—如果一个参数丢失,用户给出的剧本是如何简单的提示被使用。

I like to have a typical "usage:" line in my cmd.exe scripts—if a parameter is missing, user is given simple reminder of how the script is to be used.

问题是,我不能安全地predict潜在用户是否会使用GUI或CLI。如果使用GUI有人双击这个脚本在资源管理器窗口,他们不会有机会读任何东西,除非我暂停窗口。如果他们使用CLI,暂停会打扰他们。

The problem is that I can't safely predict whether potential user would use GUI or CLI. If somebody using GUI double-clicks this script in Explorer window, they won't have chance to read anything, unless I pause the window. If they use CLI, pause will bother them.

所以我在寻找一种方法来检测它。

So I'm looking for a way to detect it.

@echo off
if _%1_==__ (
    echo usage: %nx0: filename
    rem now pause or not to pause?
)

是否有能力,从一个批处理脚本中,检测到这一点,并在命令窗口prevent自动关闭?

推荐答案

您可以检查%CMDCMDLINE%变量的值。它包含了用于启动的cmd.exe 命令。

You can check the value of %CMDCMDLINE% variable. It contains the command that was used to launch cmd.exe.

我prepared测试.bat文件:

I prepared a test .bat file:

@Echo Off
echo %CMDCMDLINE%
pause

当从内打开的cmd.exe 窗口,脚本版画C:\\ WINDOWS \\ SYSTEM32 \\ cmd.exe的跑
当通过双击运行,它打印 CMD / CC:\\用户\\ MBU \\桌面\\ test.bat的

When run from inside of open cmd.exe window, the script prints "C:\Windows\system32\cmd.exe". When run by double-clicking, it prints cmd /c ""C:\Users\mbu\Desktop\test.bat" "

所以要检查你的脚本是通过双击你需要检查,如果%CMDCMDLINE%包含路径到脚本启动。最终的解决方案是这样的:

So to check if your script was launched by double-clicking you need to check if %cmdcmdline% contains the path to your script. The final solution would look like this:

@echo off

set interactive=1
echo %cmdcmdline% | find /i "%~0" >nul
if not errorlevel 1 set interactive=0

rem now I can use %interactive% anywhere

if _%1_==__ (
    echo usage: %~nx0 filename
    if _%interactive%_==_0_ pause
)

编辑:实施了注释中讨论的问题的变化修正;编辑例子来说明它们

implemented fixes for issues changes discussed in comments; edited example to demonstrate them

这篇关于确定批处理脚本已经从线 - 或 - 要暂停或不暂停执行的命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆