execute WshShell command from a batch script

前端 未结 4 953
一生所求
一生所求 2020-12-03 16:38

I\'ve got a simple question:

What\'s the best way to execute a single WshShell command from a Windows batch (.bat) script?

(hopefully it\'s not creating

4条回答
  •  一向
    一向 (楼主)
    2020-12-03 16:49

    This is the method I use to write a Batch-JScript hybrid script:

    @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)));
    

    For example:

    EXPR 1/3
    

    EDIT: If you want a simpler/shorter method, use this one:

    @set @a=0  /*
    @cscript //nologo //E:JScript "%~F0" "%~1"
    @goto :EOF */
    
    WScript.Echo(eval(WScript.Arguments(0)));
    

    Again, the first @set @a=0 /* is a valid statement/command in both JScript and Batch that is only used to insert the start of a JScript comment (/*), so the Batch section be ignored by JScript. The comment is closed (*/) after the final goto :EOF.

提交回复
热议问题