當我運行命令“powershell.exe -ExecutionPolicy Unrestricted -file 'C:\Users\xxxyyy\Downloads\test_script.ps1' -d 'C:\Users\xxxyyy \Downloads' -f 'TestFile'" in 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()
uj5u.com熱心網友回復:
將構成 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.exePowerShell CLI只能將'...'(單引號)字串理解為傳遞給其-Command引數的引數的一部分,而不是-File.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/531703.html
標籤:爪哇电源外壳命令行过程
下一篇:加入流的所有行
