Home > database >  Why is my script working when running from command line, but not in Java code?
Why is my script working when running from command line, but not in Java code?

Time:11-10

This powershell script that I am trying to run with Java code works when I run the command ”powershell.exe -ExecutionPolicy Unrestricted -file 'C:\Users\xxxyyy\Downloads\test_script.ps1' -d 'C:\Users\xxxyyy\Downloads' -f 'TestFile'" in powershell. The script converts an xlsx file successfully to a csv file. But when I try to run it in below test class the test is passed, but the file is not converted to csv. Can someone help me identify the issue?

Here is the code of the Java test class and the powershell script.

import org.junit.jupiter.api.Test;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class PowershellTest {

     @Test
     public void shouldConvertXlsxToCsv() {
        try {
            runCommand();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }

    public void runCommand() throws IOException {
         String[] command = new String[]{"powershell.exe","-ExecutionPolicy Unrestricted -file 'C:\\Users\\xxxyyy\\Downloads\\test_script.ps1' -d 'C:\\Users\\xxxyyy\\Downloads' -f 'TestFile'"};
         Process powerShellProcess = Runtime.getRuntime().exec(command);
         powerShellProcess.getOutputStream().close();
         BufferedReader output = new BufferedReader(new 
         InputStreamReader(powerShellProcess.getInputStream(), StandardCharsets.ISO_8859_1));

         try {
            String line;
            while ((line = output.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
           throw new RuntimeException(e);
        } finally {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

PS script:

Param(
    [string]$d,
    [string]$f
) 

$excelFile = $d   '\'   $f   ".xlsx"
$Excel = New-Object -ComObject Excel.Application
$wb = $Excel.Workbooks.Open($excelFile)

foreach ($ws in $wb.Worksheets) {
    $ws.SaveAs($d   '\'   $f   ".csv", 6)
}
$Excel.Quit()

CodePudding user response:

Pass all arguments that make up your PowerShell command line as individual array elements:

String[] command = new String[]{
  "powershell.exe",
  "-ExecutionPolicy",
  "Unrestricted",
  "-file",
  "C:\\Users\\xxxyyy\\Downloads\\test_script.ps1",
  "-d",
  "C:\\Users\\xxxyyy\\Downloads",
  "-f",
  "TestFile"
};

On a general note:

  • powershell.exe, the PowerShell CLI, would only understand '...' (single-quoted) strings as part of argument(s) passed to its -Command parameter, not with -File.
  • Related