powershell 为什么我的脚本在从命令行运行时可以运行,但在Java代码中不能运行?

2w3rbyxf  于 2022-11-10  发布在  Shell
关注(0)|答案(1)|浏览(510)

当我在PowerShell中运行命令“Powershell.exe-ExecutionPolicy un受限-FILE‘C:\USERS\xxxyyy\DOWNLOADS\TEST_SIPT.PS1’-d‘C:\USERS\xxxyyy\DOWNLOADS’-f‘TestFile’”时,我尝试用Java代码运行的这个PowerShell脚本工作正常。该脚本成功地将xlsx文件转换为CSV文件。但当我尝试在以下测试类中运行它时,测试通过了,但该文件没有转换为CSV。有人能帮我找出这个问题吗?
以下是Java测试类和PowerShell脚本的代码。

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脚本:

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()
rekjcdws

rekjcdws1#

将构成PowerShell命令行的所有参数作为单个数组元素传递:

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

概括地说:

  • powershell.exe,PowerShell CLI只会将'...'(单引号)字符串理解为传递给其-Command参数的参数的一部分,而不是与-File一起使用。

相关问题