0

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
quarks
  • 33,478
  • 73
  • 290
  • 513
  • Check this: https://stackoverflow.com/questions/9742775/why-is-my-locally-created-script-not-allowed-to-run-under-the-remotesigned-execu – Kaan Kayas Apr 01 '23 at 22:17
  • @KaanKayas yes I understand the script would not be allowed to run, my goal is to pipe the output/error/log of the process to the console. – quarks Apr 01 '23 at 22:50
  • What is the return type and exact value of `loadFileCommand()` – DuncG Apr 02 '23 at 12:08
  • Here `powershell.exe -File \path\to\temp_file_.ps1` – quarks Apr 03 '23 at 14:26

0 Answers0