Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何检测脚本是否被调用';是否在Windows CMD.EXE shell中直接调用?_Windows_Cmd - Fatal编程技术网

如何检测脚本是否被调用';是否在Windows CMD.EXE shell中直接调用?

如何检测脚本是否被调用';是否在Windows CMD.EXE shell中直接调用?,windows,cmd,Windows,Cmd,我需要在script.cmd中区分这两种情况: C:\> call script.cmd C:\> script.cmd 如何确定是直接调用我的script.cmd,还是在使用调用的上下文中调用 如果重要的话,这是在Windows7上 @echo off set invoked=0 rem ---magic goes here--- if %invoked%==0 echo Script invoked directly. if %invoked%==1 echo Script i

我需要在script.cmd中区分这两种情况:

C:\> call script.cmd
C:\> script.cmd
如何确定是直接调用我的script.cmd,还是在使用调用的上下文中调用

如果重要的话,这是在Windows7上

@echo off
set invoked=0
rem ---magic goes here---
if %invoked%==0 echo Script invoked directly.
if %invoked%==1 echo Script invoked by a CALL.

任何人都知道“魔法在这里”会检测到被调用并设置为调用=1吗?

目前,我看不出有办法检测到它,但作为一种解决方法,您可以随时强制使用哨兵

@echo关闭
setLocalEnableExtensions
rem如果“标志”不存在,使用CALL命令
如果不是“%~1”=”\u标志\u转到:使用调用
rem丢弃“标志”
班次/1
这里是主代码
设置/a“randomExitCode=%Randomy%%%2”
echo[%~1]退出,代码为%randomExitCode%
退出/b%randomExitCode%
后藤:eof
rem检索对当前批处理文件的正确完整引用
:getBatchReference returnVar
设置“%~1=%~f0”&转到:eof
rem执行
:useCall
setlocal enableextensions disabledelayedexpansion
调用:getBatchReference\u f0
endlocal&调用“%\u f0%”\u标志%*
这将允许您使用指定的语法

script.cmd first && script.cmd second && script.cmd third
发布的代码以随机退出代码结束脚本以进行测试。退出代码为0时将继续执行


注意:至少在XP中,对批处理文件的
调用必须是批处理文件中的最后一个代码,这样做可以解决什么问题?它解决了能够执行以下操作的问题
script1.cmd&&script2.cmd&&script3.cmd
…无需执行
call script1.cmd&&call script2.cmd&&call script3.cmd
No,在知道如何调用文件的情况下,无法“解决”指示的“问题”。批处理解释器决定执行流是否返回调用方(当使用
调用
时)或不返回(不使用
调用
)。在您评论中的示例代码中,在这两种情况下调用这三个文件都没有问题。如果script1.cmd有
@call script1_impl.cmd%*
,然后script1_impl.cmd有了实现,那么
script1&&script2&&script3
带有错误中止的链接将起作用。如果不需要一个脚本就可以进行脚本转发(call'ing),那就太好了。可以使用%1的sentinel标记调用它自己。@MCND如果脚本是通过
调用调用的,则CMD
&&
将遵守脚本返回的errorlevel。如果脚本不是通过
调用调用调用的,则CMD不会接受脚本返回的errorlevel。我最终使用了相同的技术。似乎它应该是某种可以通过某种方式访问的东西。现在我希望我在微软工作的时候能看看CMD的源代码。sadpandaWord警告,如果需要执行
script1^ |和&script2^>和&script3
%*
无法正确转义转义参数。在我的用例中,这不是一个问题,因为我的参数是简单的单词。但是我在单元测试中发现了这个问题。我可能缺少一个
%~*
或类似的可以正确扩展参数的程序。太麻烦了。我推荐PowerShell。哈哈,我喜欢你的想法比尔·斯图尔特!虽然如果我使用另一个shell,我会使用Cygwin Bash。不幸的是,在这种情况下,PowerShell和Cygwin Bash都不是可行的选择。必须是Windows CMD shell。PowerShell在运行CMD.exe脚本时没有问题。我不是说包装任何东西;切换到PowerShell作为shell,而不是cmd.exe。这是一个更好的指挥环境。