2

我正在尝试使用cscriptand来编写 Windows shell 脚本Javascript。这个想法是采用一个非常长的 Python 命令,我厌倦了一遍又一遍地输入命令行。我想要做的是编写一个更短的脚本,将整个 Python 命令写入 Windows 脚本,然后调用 Windows 脚本,这样输入起来会少很多。如果有意义的话,我只是不知道如何调用“命令中的命令”。

这可能是一件容易的事情,但我是这方面的新手,所以请多多包涵!

想法:

示例原始命令:python do <something really complicated with a long filepath>

视窗脚本:cscript easycommand

 <package id = "easycommand">
      <job id = "main" >
          <script type="text/javascript">
               // WHAT GOES HERE TO CALL python do <something really complicated>
               WScript.Echo("Success!");
          </script>
      </job>
 </package>

感谢你的帮助!

4

2 回答 2

4

这是我使用的

function logMessage(msg) {
    if (typeof wantLogging != "undefined" && wantLogging) {
        WScript.Echo(msg);
    }
}

// http://msdn.microsoft.com/en-us/library/d5fk67ky(VS.85).aspx
var windowStyle = {
    hidden    : 0,
    minimized : 1,
    maximized : 2
};

// http://msdn.microsoft.com/en-us/library/a72y2t1c(v=VS.85).aspx
var specialFolders = {
    windowsFolder   : 0,
    systemFolder    : 1,
    temporaryFolder : 2
};

function runShellCmd(command, deleteOutput) {
    deleteOutput = deleteOutput || false;
    logMessage("RunAppCmd("+command+") ENTER");
    var shell = new ActiveXObject("WScript.Shell"),
        fso = new ActiveXObject("Scripting.FileSystemObject"),
        tmpdir = fso.GetSpecialFolder(specialFolders.temporaryFolder),
        tmpFileName = fso.BuildPath(tmpdir, fso.GetTempName()),
        rc;

    logMessage("shell.Run("+command+")");

    // use cmd.exe to redirect the output
    rc = shell.Run("%comspec% /c " + command + "> " + tmpFileName,
                       windowStyle.Hidden, true);
    logMessage("shell.Run rc = "  + rc);

    if (deleteOutput) {
        fso.DeleteFile(tmpFileName);
    }
    return {
        rc : rc,
        outputfile : (deleteOutput) ? null : tmpFileName
    };
}

下面是一个示例,说明如何使用上述方法列出在 IIS 中使用 Appcmd.exe 定义的站点:

var
fso = new ActiveXObject("Scripting.FileSystemObject"),
windir = fso.GetSpecialFolder(specialFolders.WindowsFolder),
r = runShellCmd("%windir%\\system32\\inetsrv\\appcmd.exe list sites");
if (r.rc !== 0) {
    // 0x80004005 == E_FAIL
    throw {error: "ApplicationException",
           message: "shell.run returned nonzero rc ("+r.rc+")",
           code: 0x80004005};
}

// results are in r.outputfile

var
textStream = fso.OpenTextFile(r.outputfile, OpenMode.ForReading),
sites = [], item, 
re = new RegExp('^SITE "([^"]+)" \\((.+)\\) *$'),
parseOneLine = function(oneLine) {
    // each line is like this:  APP "kjsksj" (dkjsdkjd)
    var tokens = re.exec(oneLine), parts;

    if (tokens === null) {
        return null;
    }
    // return the object describing the website
    return {
        name : tokens[1]
    };
};

// Read from the file and parse the results.
while (!textStream.AtEndOfStream) {
    item = parseOneLine(textStream.ReadLine()); // you create this...
    logMessage("  site: " + item.name);
    sites.push(item);
}
textStream.Close();
fso.DeleteFile(r.outputfile);
于 2012-07-02T21:35:32.477 回答
1

好吧,基本上:

  1. 获取 shell 的句柄,以便您可以执行脚本
  2. 将要执行的命令(参数和所有)创建为字符串
  3. 调用Runshell 句柄上的方法,并确定您想要哪种窗口模式以及是否要等到生成的进程完成(可能)。
  4. 错误处理,因为Run抛出异常

在这一点上,如果您需要多次执行此操作,则值得编写大量实用函数:

// run a command, call: run('C:\Python27\python.exe', 'path/to/script.py', 'arg1', 'arg2') etc.
function run() {
  try {
    var cmd = "\"" + arguments[0] + "\"";
    var arg;
    for(var i=1; i< arguments.length; ++i) {
      arg = "" + arguments[i];
      if(arg.length > 0) {
    cmd += arg.charAt(0) == "/" ? (" " + arg) : (" \"" + arg + "\"");
      }
    }
    return getShell().Run(cmd, 1, true); // show window, wait until done
  }
  catch(oops) {
    WScript.Echo("Error: unable to execute shell command:\n"+cmd+ 
             "\nInside directory:\n" + pwd()+
         "\nReason:\n"+err_message(oops)+
         "\nThis script will exit.");
    exit(121);
  }
}

// utility which makes an attempt at retrieving error messages from JScript exceptions
function err_message(err_object) {
  if(typeof(err_object.message) != 'undefined') {
    return err_object.message;
  }
  if(typeof(err_object.description) != 'undefined') {
    return err_object.description;
  }
  return err_object.name;
}

// don't create new Shell objects each time you call run()
function getShell() {
  var sh = WScript.CreateObject("WScript.Shell");
  getShell = function() {
    return sh;
  };
  return getShell();
}

对于您的用例,这可能就足够了,但您可能希望使用例程来扩展它以更改工作目录等。

于 2012-06-28T00:41:21.033 回答