简体   繁体   English

从javascript运行bat文件

[英]Run a bat file from javascript

I'm trying to run a bat file using javascript.我正在尝试使用 javascript 运行 bat 文件。 I've tried using powershell but it didn't seem to work properly.我试过使用 powershell,但它似乎无法正常工作。 Here is the code I tried:这是我试过的代码:

var oShell = WScript.CreateObject("WScript.Shell");
oShell.Exec("D:");
oShell.Exec("cd dir");
oShell.Exec("start user.bat");

I've also tried that:我也试过:

var oShell = WScript.CreateObject("WScript.Shell");
oShell.Exec("start D:\dir\user.bat");

Sometimes it runs, sometimes I get those errors "Expected hexadecimal digit", "Access is denied".有时它会运行,有时我会收到这些错误“预期的十六进制数字”、“访问被拒绝”。 I'm really confused.我真的很困惑。 All I'm trying to do is execute a bat file from a javascript file.我想要做的就是从一个 javascript 文件执行一个 bat 文件。

Anyone has any idea how to do it?任何人都知道该怎么做? Thank you!谢谢!

First, JavaScript doesn't have any operating system services.首先,JavaScript 没有任何操作系统服务。 So you are really referring to a Windows Script Host (WSH) script that happens to be written in JavaScript.因此,您实际上是指碰巧用 JavaScript 编写的 Windows Script Host (WSH) 脚本。

Second, start is not an executable but rather a command that is built into cmd.exe .其次, start不是一个可执行文件,而是一个内置于cmd.exe的命令。

With the confusion out of the way, it sounds like you want to execute a shell script (batch file) from a WSH script.消除混乱,听起来您想从 WSH 脚本执行 shell 脚本(批处理文件)。 The simplest way is like this (this is somewhat close to what you tried already):最简单的方法是这样的(这有点接近你已经尝试过的):

var wshShell = new ActiveXObject("WScript.Shell");
wshShell.Run("D:\\dir\\user.bat");

To create the WshShell COM object reference (progid WScript.Shell ), use the new keyword and the ActiveXObject constructor.要创建WshShell COM 对象引用(progid WScript.Shell ),请使用new关键字和ActiveXObject构造函数。 Also, you need to double your backslashes ( \\ ) in JavaScript strings because \\ escapes characters in JavaScript strings.此外,您需要将 JavaScript 字符串中的反斜杠 ( \\ ) 加倍,因为\\转义 JavaScript 字符串中的字符。

Also, check the following version it might help;另外,检查以下版本可能会有所帮助;

var runnableScript = exec('path_to.bat',
    (error, stdout, stderr) => {
        console.log(stdout);
        console.log(stderr);
        if (error !== null) {
            console.log(`exec error: ${error}`);
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM