簡體   English   中英

在Windows上使用javascript(nashorn)進行命令行腳本

[英]Command line scripting with javascript (nashorn) on windows

我想在Windows下使用javascript(特別是nashorn)進行命令行腳本編寫。 通過命令行腳本,我的意思是使用javascript而不是.bat文件來執行各種命令行實用程序並處理其輸出。 一個正式的例子在oracle上

它們在那里展示了如何使用$EXEC("ls -l").js文件中執行shell命令,並且如果使用以下命令運行,則可以在$OUT$ERR訪問$OUT
jjs script.js -scripting -- params 我做了很多谷歌搜索,但是在Windows上不支持此功能(oracle和3rd party博客文章,SO等),但無論如何, 所有示例都使用bash命令。 在Windows上甚至可能嗎?
所以我可以寫一個.js腳本嗎? $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 ./")也會失敗,並出現同樣的“找不到文件”錯誤),但是您可以使用以下命令運行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 ,因此它的所有限制也都適用於此。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM