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

Command line scripting with javascript (nashorn) on windows

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

那里展示了如何使用 $EXEC("ls -l").js 文件中执行 shell 命令,并且可以在 $OUT 和 [=16= 中访问输出],如果你 运行 它与
jjs script.js -scripting -- params。我做了很多谷歌搜索,但在任何地方(甲骨文和第 3 方博客文章,SO 等)都没有提到 windows 不支持它,但不知何故,all 的示例带有 bash 命令。 这甚至可以在 windows 上实现吗?
那么我可以写在 .js 脚本中吗? $EXEC("dir") 并处理 $OUT 的输出?

我走了多远:

我在这里错过了什么?任何想法表示赞赏。

环境详情:

异常:

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

On 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

...

或者调用一些非交互的可执行文件,比如label

$EXEC("label C:System")

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

顺便说一句,internally Nashorn uses good old java.lang.ProcessBuilder 代表 $EXEC,因此它的所有限制也适用于此。