I have this scenario in which I need to execute commands and pass arguments to the command in Java:
public void execute() throws IOException, InterruptedException {
// Save the script to a temporary file
Path tempScriptFile = Files.createTempFile("temp_script_", getExtension());
Files.write(tempScriptFile, scriptText.getBytes(StandardCharsets.UTF_8), StandardOpenOption.WRITE);
// Build the process command and arguments
ProcessBuilder builder = new ProcessBuilder(loadFileCommand(tempScriptFile.toString()));
builder.redirectErrorStream(true);
builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
Process process = builder.start();
//String output = ProcessUtil.getProcessOutput(process);
// Wait for the process to complete and print the exit code
int exitCode = process.waitFor();
System.out.println("Script execution finished with exit code " + exitCode);
// Clean up the temporary script file
Files.delete(tempScriptFile);
System.exit(exitCode);
}
So far, this code works fine and the command is executed, the problem is when an error occurs like (manually running the command):
> powershell.exe -File \path\to\temp_file_.ps1
File \path\to\temp_file_.ps1 cannot be loaded. The file \path\to\temp_file_.ps1 is not
digitally signed. You cannot run this script on the current system. For more information about running scripts and
setting execution policy, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
+ CategoryInfo : SecurityError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnauthorizedAccess
I am expecting this same error to be printed too when the Java execute
is used to run the command, but it does not, it exits without that expected error:
Script execution finished with exit code 0
Disconnected from the target VM, address: '127.0.0.1:57457', transport: 'socket'
Process finished with exit code 0