我创建了一个Java程序,在按下按钮后运行VBSscripts。
examplescript.vbs
如何编译这些vbs文件然后调用它们在程序代码中运行?我已经进行了几天的故障排除,但找不到答案。我再次需要能够运行这些脚本,有一次我创建了一个输入流,但无法将其作为vbs文件获取。希望我在这里忽略了一些东西
编辑: 这就是我现在拥有的。使用此代码,我收到错误“Windows脚本主机。文件扩展名没有脚本扩展名”.BufferedInputStream @ 4e34904“”
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("hello.vbs");
try {
Runtime.getRuntime().exec("wscript " + is);
}
catch( IOException e ) {
System.out.println(e);
System.exit(0);
}
System.out.print(is);
答案 0 :(得分:0)
您可以按如下方式运行VBScript。
Runtime.getRuntime().exec( "wscript path/to/examplescript.vbs" );
答案 1 :(得分:0)
如前所述,VBScript是一个脚本,不需要编译。如果你想运行用VBScript编写的代码,那么你可以这样做:
此示例使用VBScript获取运行Microsoft Windows的计算机的主板序列号:
try {
// Create a temporary script file named MBSerialxxxxxxxx.vbs
File file = File.createTempFile("MBSerial",".vbs");
// Delete the temporary file when virtual machines terminates
file.deleteOnExit();
try (FileWriter fw = new java.io.FileWriter(file)) {
String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
+ "Set colItems = objWMIService.ExecQuery _ \n"
+ " (\"Select * from Win32_BaseBoard\") \n"
+ "For Each objItem in colItems \n"
+ " Wscript.Echo objItem.SerialNumber \n"
+ " exit for ' do the first cpu only! \n"
+ "Next \n";
fw.write(vbs);
}
// Run the VBScript file....
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
// Read in any output to the command window.
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
// display the output...
System.out.println(line.trim());
}
input.close();
}
catch(IOException e){
e.printStackTrace();
}