用于调用其他命令的 Windows 脚本

Windows Scripting to call other commands?

本文关键字:Windows 脚本 命令 调用 其他 用于      更新时间:2023-09-26

我正在尝试使用cscriptJavascript编写Windows shell脚本。这个想法是采用一个很长的 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>

感谢您的帮助!

这是我

使用的

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
    };
}

下面是如何使用上述内容列出使用 Appcmd .exe 在 IIS 中定义的站点的示例:

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

嗯,基本上:

  1. 获取 shell 的句柄,以便执行脚本
  2. 将要执行的命令(参数和所有)创建为字符串
  3. 在 shell 句柄上调用 Run 方法,并确定您想要哪种窗口模式,以及是否要等到生成的进程完成(可能)。
  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();
}

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