[英]Java calling Powershell script with function and not returning Write-Host to java
我正在使用 Java 調用 powershell 腳本。 powershell 腳本是使用 function 構建的,function 會將值寫入控制台。 我需要在 java 中捕獲這些值。 我的 poweshell 腳本如下
$TokenCSV="M:\work\Powershell\TokenExtractedFromDB_Spec.csv"
$TokenXlPath="M:\work\Powershell\TokenListconverted.xlsx"
$Switch="Token"
Write-Host "Inside ConvertCSVtoEXL2 calling fuc :"
$x=ConverToExlFile $TokenCSV $TokenXlPath $Switch
###Function
function ConverToExlFile
{
Param ([string]$TokenCSV,
[string]$TokenXlPath,
[string]$Switch)
Write-Output "Inside ConverToExlFile Function :"| Out-Null
for($row = 2;$row -lt 10;$row++)
{
Write-Output "Inside for loop :$row"| Out-Null
}
return
}
通過 java 調用上述代碼時,我沒有在 while 循環中獲取值,如下所示。 一旦 powershell 腳本執行,它就會完成。
Process proc = runtime.exec("cmd.exe /c powershell.exe M:\\work\\Powershell\\V2\\ConvertCSVtoEXL2.ps1");
System.out.println("2...");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
String line;
System.out.println("3");
while ((line = reader.readLine()) != null)
{
System.out.println(line);
//System.out.println(reader.readLine());
System.out.println("4");
}
如果有人可以幫助我,那就太好了。
cmd.exe
。 您可以直接運行powershell.exe
。Out-Null
,因此顯然不會將任何內容寫入標准 output。powershell.exe
接受可用於運行腳本的-File
參數。import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class PrcBldTs {
public static void main(String[] args) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("powershell.exe", "-File", "M:\\work\\Powershell\\V2\\ConvertCSVtoEXL2.ps1");
Process p = pb.start();
try (InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(isr)) {
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
}
int exitStatus = p.waitFor();
System.out.println("exit status = " + exitStatus);
}
}
請注意,您必須調用方法waitFor()
以便您的 java 代碼將等到PowerShell腳本終止。
請記住, ProcessBuilder
不會模擬 Windows 命令提示符。 在ProcessBuilder
構造函數中,您需要將傳遞的命令拆分為單詞列表。
當然,如果您只想打印PowerShell腳本 output,您可以簡單地調用 class ProcessBuilder
的方法redirectIO()
。 那么上面的代碼就變成了:
import java.io.IOException;
public class PrcBldTs {
public static void main(String[] args) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("powershell.exe", "-File", "M:\\work\\Powershell\\V2\\ConvertCSVtoEXL2.ps1");
pb.inheritIO();
Process p = pb.start();
int exitStatus = p.waitFor();
System.out.println("exit status = " + exitStatus);
}
}
你可以使用proc.waitFor();
在從 proc 獲取輸入 stream 之前
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.