=====Running an Executable from a Script=====
In MIStudio you can use the CommmandExecutor to run an external executable or script (.sh or .bat). In a script you can use the Java Runtime and create a Process to run a command.
====Simple Example with One Parameter====
var Runtime = Java.type("java.lang.Runtime");
var Process = Java.type("java.lang.Process");
//This runs the external program
//Consider running this in its own Thread
try
{
// Command to create an external process
command = "notepad";
// Running the above command
run = Runtime.getRuntime();
proc = run.exec(command); //will launch notepad.exe on windows
} catch (e) {
print("error in script: \n"+e.stack);
}
output="finished";
====Example with a Command Array====
In this example we need to run a CMD shell to launch a PDF viewer. This will run the default viewer on the system using Windows start.
var Runtime = Java.type("java.lang.Runtime");
var Process = Java.type("java.lang.Process");
pdfname="C:/Reports/SummaryReport_2023-01-24_12-58-26.pdf";
//launch pdf viewer using Windows START
command = ["cmd.exe","/c","start",pdfname];
try {
print("command for launching pdf viewer: "+command);
rt = Runtime.getRuntime();
proc = rt.exec(command);
} catch (e) {
print("error in script: \n"+e.stack);
}
incomingValue;
====Running a Command with an Output====
Sometimes you might need to run a command or script on a system and need to capture the output of the exec. In the example below the Windows tzutil (time zone utility) to return a time zone string. The command is "tzutil /g". The return string will be something such as "Pacific Standard Time".
In this example we have set up a BroadcastServer (Variable) called "LocalTimeZone" under UtilityServers in Devices. The result is stored in this BCS.
//test script to read the local time zone and store it in a BCS "LocalTimeZone"
var Runtime = Java.type("java.lang.Runtime");
var Process = Java.type("java.lang.Process");
var BufferedReader = Java.type("java.io.BufferedReader");
var InputStreamReader = Java.type("java.io.InputStreamReader");
//get the local time zone for this Windows system using tzutil /g
command = ["tzutil","/g"];
timezone="";
try {
//print("command: "+command);
rt = Runtime.getRuntime();
proc = rt.exec(command);
//proc contains the return value, a string, but is an InputStream, so need to read it one line at a time (should only be one line in this example)
resultLine="";
stdIn = new BufferedReader(new InputStreamReader (proc.getInputStream()));
while ((resultLine = stdIn.readLine()) != null) {
timezone=timezone+resultLine;
}
print ("timezone is :"+timezone);
//store the value
/Devices/DemoServers_Servers/LocalTimeZone->setStringValue(timezone);
} catch (e) {
print("error in script: \n"+e.stack);
}
incomingValue;