在windows上使用javascript (nashorn)编写命令行脚本

Command line scripting with javascript (nashorn) on windows

本文关键字:命令行 脚本 nashorn windows javascript      更新时间:2023-09-26

我想在windows下使用javascript(特别是nashorn)命令行脚本。通过命令行脚本,我的意思是使用javascript而不是.bat文件来执行各种命令行实用程序并处理其输出。这里有一个官方的例子。

显示了如何使用$EXEC("ls -l").js文件中执行shell命令,如果使用
运行,可以在$OUT$ERR中访问输出jjs script.js -scripting -- params。我做了很多谷歌搜索,并没有提到任何地方(oracle和第三方博客文章,SO等),这是不支持windows,但不知怎的,所有的例子都与bash命令。这在windows上可能吗?
所以我可以写在.js脚本eg。$EXEC("dir")并处理$OUT的输出?

我走了多远:

  • 如果我不使用jjs-scripting参数,当脚本命中$EXEC命令时,我只是得到ReferenceError: "$EXEC" is not defined,所以这可能不是要走的路。

  • 如果我使用-scripting参数,$EXEC("cd c:")抛出下面的异常。这表明我可能以错误的方式调用命令,或者路径或其他东西没有正确设置。

我在这里错过了什么?如有任何意见,不胜感激。

环境细节:

  • 8.1赢得

  • Java 8, jjs (bin)的路径设置在系统的环境变量中

例外:

Exception in thread "main" java.lang.RuntimeException: java.io.IOException: Cannot run program "cd": CreateProcess error=2, The system cannot find the file specified
        at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:382)
        at jdk.nashorn.tools.Shell.apply(Shell.java:383)
        at jdk.nashorn.tools.Shell.runScripts(Shell.java:312)
        at jdk.nashorn.tools.Shell.run(Shell.java:168)
        at jdk.nashorn.tools.Shell.main(Shell.java:132)
        at jdk.nashorn.tools.Shell.main(Shell.java:111)
Caused by: java.io.IOException: Cannot run program "cd": CreateProcess error=2, The system cannot find the file specified
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
        at jdk.nashorn.internal.runtime.ScriptingFunctions.exec(ScriptingFunctions.java:166)
        at jdk.nashorn.internal.scripts.Script$test01.runScript(test01.js:8)
        at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:535)
        at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:209)
        at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:378)
        ... 5 more
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
        at java.lang.ProcessImpl.create(Native Method)
        at java.lang.ProcessImpl.<init>(ProcessImpl.java:386)
        at java.lang.ProcessImpl.start(ProcessImpl.java:137)
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
        ... 10 more

在Windows上cddir是shell命令,而不是系统可执行文件(即使在Linux上$EXEC("cd ./")也会以相同的"cannot find the file"错误失败),但是您可以使用命令运行bat脚本:

test.bat包含 时

cd C:'Users
pwd

jjs

$EXEC("./test.bat")

将打印

Volume in drive C has no label.
Volume Serial Number is ...
Directory of C:'Users
...

或调用一些非交互式可执行文件,如标签

$EXEC("label C:System")

(这只是我在system32文件夹中发现的第一个非交互式的东西;可能会因为权限不足而失败(假设您以非管理员身份运行jjs)

顺便说一下,在内部,Nashorn为$EXEC使用了旧的java.lang.ProcessBuilder,所以它的所有限制也适用于这里。