确定是否已从命令行(cmd)启动/执行批处理脚本-或-要暂停还是不暂停? [英] Determining if batch script has been started/executed from the command line (cmd) -or- To pause or not to pause?

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

问题描述

我喜欢在我的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.

问题是我无法安全地预测潜在用户将使用GUI还是CLI.如果有人使用GUI在资源管理器窗口中双击此脚本,则除非我pause窗口,否则他们将没有机会阅读任何内容.如果他们使用CLI,pause会打扰他们.

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?
)

在这方面有很好的解决方案吗?

Is there a nice solution on this?

推荐答案

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

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

我准备了一个测试.bat文件:

I prepared a test .bat file:

@Echo Off
echo %CMDCMDLINE%
pause

从打开的cmd.exe窗口内部运行时,脚本将打印"C:\Windows\system32\cmd.exe". 双击运行时,将显示cmd /c ""C:\Users\mbu\Desktop\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

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

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