如何在当前批处理中调用另一个批处理文件中定义的函数?
我知道我可以使用 call path_to_other_batch_file.bat
调用另一个批处理文件。
但是,我不知道如何调用该文件内的函数。
我有一个名为 Message.bat
的批处理文件:
@echo off
EXIT /B %ERRORLEVEL%
:Error
echo [31m %* [0m
EXIT /B 0
:Warning
echo [33m %* [0m
EXIT /B 0
:Info
echo [34m %* [0m
EXIT /B 0
:Success
echo [32m %* [0m
EXIT /B 0
:Reset
echo [37m %* [0m
EXIT /B 0
我想在其他批处理文件中使用这些函数,这样我就可以简单地编写 call:Error Something goneError
而不必担心一直与颜色有关。
我在 Other.bat
中以这种方式使用它,但它不起作用:
call C:\Infra\Message.bat
call:Error something went wrong
我收到此错误:
系统找不到指定的批次标签 - 错误
那么,如何调用 Message.bat
文件中定义的这些方法呢?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在你的主要批次中
在消息中
确实没那么难...
或者,在 message.bat 中更好
...
In your main batch(es)
In message
really not that hard...
or, better in message.bat
...
(至少)有两种可能性,其中一种是由 jeb 提供的"https://stackoverflow.com/a/60040042" title="为什么我们不能在 FORFILES 脚本中使用 CALL :label 命令?">他的这个回答 – 所以请给予他足够的信任通过投票支持他的 邮政!
main.bat
,在sub.bat
中建立两次标签:Label
的调用:sub.bat
,以两种不同的方式解析标签:Label
:这是运行
main.bat
时的控制台输出:您可能已经注意到,在第一次调用中,标签
:Label
也是参数字符串%*
的一部分,您必须特别注意,尽管在第二次调用(应用所述 jeb 的方法),%*
包含纯没有额外项目的参数字符串。There are (at least) the two possibilities, one of which is courtesy of user jeb in this answer of him – so please give adequate credit to him by up-voting his post!
main.bat
, establishing two calls of label:Label
insub.bat
:sub.bat
, resolving label:Label
in two distinct ways:And this is the console output upon running
main.bat
:As you may have noticed, in the first call, the label
:Label
is also part of the argument string%*
which you have to pay specific attention to, though in the second call (applying said jeb's method),%*
contains the pure argument string without an extra item.如果您有多个选项,标签有时会变得混乱。如果某些任务满足标准,那么这对于多项任务很有用,但您似乎只想更改事件的颜色。所以我只想说根本不要使用标签。
message.bat
的内容添加:要从另一个批次中调用此内容,只需执行以下操作:
您很可能也想将实际的严重性添加到消息中,而不仅仅是更改文本颜色,然后简单地将范围缩小到:
Labels can sometimes become cluttered if you have multiple options. It is good for multiple tasks if some meets the criteria, but you seem to only want to change colors on events. So I will simply say do not use labels at all. The content of
message.bat
add:To call this from another batch, simply do:
There is an odd chance that you want to add the actual severities into the message as well, and not just change the text color, then simply narrow it down to:
没有内在的方法可以做到这一点。
呼叫
将在当前文件中调用外部文件,内部命令或标签 。但是,如果您可以更改
message.bat
,则可以使其添加其他参数,呼叫
IT。然后,呼叫
将在其自己的标签中搜索。您必须格外小心,而不是将第一个参数传递给标签。为此,您可以使用
。
There's no built-in way to do that.
call
will either call an external file, an internal command or a label in the current file.But, if you can change
message.bat
, you can make it take an additional argument, andcall
it. Thencall
will search in its own labels.You'll have to take extra care to not pass the first argument to the label. For that, you can use the code from this answer:
Then, you can call it like: