从批处理脚本执行WshShell命令

Ole*_*eev 3 windows wsh batch-file

我有一个简单的问题:

从Windows批处理(.bat)脚本执行单个WshShell命令的最佳方法是什么?

(希望它不是用VB代码创建一个新文件)

dbe*_*ham 7

您可以通过VBScript或Jscript访问WshShell.两者都可以嵌入批处理文件中,但JScript更清晰.

大多数人通过编写临时VBS文件来批量执行VBScript.但是没有临时文件就可以做到这一点.请参阅是否可以在批处理文件中嵌入和执行VBScript而不使用临时文件?各种选择.

在批处理中嵌入JScript非常简单.请参阅/sf/answers/395937531/.我使用了这种技术的一个非常小的变化.

@if (@X)==(@Y) @end /* Harmless hybrid line that begins a JScript comment

:: ******* Begin batch code *********
@echo off
:: Your batch logic goes here

:: At any point you can execute the following to access your JScript
cscript //E:JScript //nologo "%~f0" yourJscriptParametersGoHere

:: Be sure to terminate your script so that 
:: it does not fall through into the JScript code
exit /b

********* Begin JScript code **********/
var WshShell=WScript.CreateObject("WScript.Shell")

/* do whatever with your WshShell object */
Run Code Online (Sandbox Code Playgroud)

说明:

该技术的关键是第一线.它必须是具有JScript和批处理的有效语法的行.

Batch将第一行看作一个总是求值为false的简单IF命令,因此它永远不会执行不存在的@end命令,并且不会造成任何损害.在达到exit/b之前,以下行都是正常的批处理代码,此时批处理将终止,其余行将被忽略.

JScript将第一行视为空条件编译块,然后是多行注释的开头.JScript忽略以下批处理代码,因为它是注释的全部内容.注释以*/,然后是普通的JScript代码结束.

唯一可能失败的是你的批处理代码必须包含*/在其中,因为这会过早地终止JScript注释.但是,这可以通过将之间的事情要解决*,并/批量解析后消失.如果没有引用代码,那么你可以简单地转义斜杠,如下所示:*^/.如果代码被引用,那么您可以展开一个未定义的变量:*%=%/.=保证不定义名为的变量.


Aac*_*ini 7

这是我用来编写Batch-JScript混合脚本的方法:

@if (@CodeSection == @Batch) @then

:: The first line above is...
:: in Batch: a valid IF command that does nothing.
:: in JScript: a conditional compilation IF statement that is false,
::             so this section is omitted until next "at-sign end".


@echo off

rem EXPR.BAT: Evaluate a JScript (arithmetic) expression
rem Antonio Perez Ayala

rem Define an auxiliary variable to call JScript
set JSCall=Cscript //nologo //E:JScript "%~F0"

rem Do Batch business here, for example:
%JSCall% %1
goto :EOF

End of Batch section


@end


// JScript section

WScript.Echo(eval(WScript.Arguments.Unnamed.Item(0)));
Run Code Online (Sandbox Code Playgroud)

例如:

EXPR 1/3
Run Code Online (Sandbox Code Playgroud)

编辑:如果你想要一个更简单/更短的方法,使用这个:

@set @a=0  /*
@cscript //nologo //E:JScript "%~F0" "%~1"
@goto :EOF */

WScript.Echo(eval(WScript.Arguments(0)));
Run Code Online (Sandbox Code Playgroud)

同样,第一个@set @a=0 /*是JScript和Batch中的有效语句/命令,仅用于插入JScript注释(/*)的开头,因此JScript会忽略Batch部分.评论在决赛结束后关闭(*/)goto :EOF.