从javascript运行bat文件 [英] Run a bat file from javascript

查看:1767
本文介绍了从javascript运行bat文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用javascript运行bat文件.我已经尝试过使用Powershell,但它似乎无法正常工作.这是我尝试的代码:

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:

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

我也尝试过:

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

有时它运行,有时会出现错误预期的十六进制数字",访问被拒绝". 我真的很困惑我要做的就是从javascript文件执行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.

任何人都知道该怎么做吗?谢谢!

Anyone has any idea how to do it? Thank you!

推荐答案

首先,JavaScript没有任何操作系统服务.因此,您实际上指的是恰巧是用JavaScript编写的Windows脚本宿主(WSH)脚本.

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.

第二,start不是可执行文件,而是内置在cmd.exe中的命令.

Second, start is not an executable but rather a command that is built into cmd.exe.

混乱不堪,听起来您想从WSH脚本执行Shell脚本(批处理文件).最简单的方法是这样的(这与您已经尝试过的方法有些接近):

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):

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

要创建WshShell COM对象引用(progid WScript.Shell),请使用new关键字和ActiveXObject构造函数.另外,由于\会转义JavaScript字符串中的字符,因此您需要将JavaScript字符串中的反斜杠(\)加倍.

To create the WshShell COM object reference (progid WScript.Shell), use the new keyword and the ActiveXObject constructor. Also, you need to double your backslashes (\) in JavaScript strings because \ escapes characters in JavaScript strings.

这篇关于从javascript运行bat文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆