Javascript 从javascript运行bat文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42985964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run a bat file from javascript
提问by morha13
I'm trying to run a bat file using javascript. I've tried using powershell but it didn't seem to work properly. Here is the code I tried:
我正在尝试使用 javascript 运行 bat 文件。我试过使用 powershell,但它似乎无法正常工作。这是我试过的代码:
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!
任何人都知道该怎么做?谢谢!
回答by Bill_Stewart
First, JavaScript doesn't have any operating system services. So you are really referring to a Windows Script Host (WSH) script that happens to be written in JavaScript.
首先,JavaScript 没有任何操作系统服务。因此,您实际上是指碰巧用 JavaScript 编写的 Windows Script Host (WSH) 脚本。
Second, startis 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. The simplest way is like this (this is somewhat close to what you tried already):
消除混乱,听起来您想从 WSH 脚本执行 shell 脚本(批处理文件)。最简单的方法是这样的(这有点接近你已经尝试过的):
var wshShell = new ActiveXObject("WScript.Shell");
wshShell.Run("D:\dir\user.bat");
To create the WshShellCOM object reference (progid WScript.Shell), use the newkeyword and the ActiveXObjectconstructor. Also, you need to double your backslashes (\) in JavaScript strings because \escapes characters in JavaScript strings.
要创建WshShellCOM 对象引用 (progid WScript.Shell),请使用new关键字和ActiveXObject构造函数。此外,您需要将\JavaScript 字符串中的反斜杠 ( )加倍,因为 JavaScript 字符串中的\字符会被转义。
回答by Atakan Atamert
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}`);
}
});

