java - Java用函数调用Powershell脚本并且不将Write-Host返回给java
问题描述
我正在使用 Java 调用 powershell 脚本。powershell 脚本是用函数构建的,该函数会将值写入控制台。我需要在 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
。 - 您的PowerShell脚本正在将输出发送到,
Out-Null
因此显然不会将任何内容写入标准输出。 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脚本输出,您可以简单地调用redirectIO()
class 的方法ProcessBuilder
。那么上面的代码就变成了:
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);
}
}
推荐阅读
- subscription - 为什么 Subscription on Created 不适用于 Prisma?
- css - CSS 和 SCSS/SASS 变量中的自定义属性之间的区别
- mysql - Angular - 在 Zeppelin 中将动态表单内容插入数据库
- android - 创建为您提供位置的按钮 (Android Studio)
- go - 如何在 nats 中回复已接受的连接。在 golang 中订阅
- ios - 将 PHAsset 转换为 UIImage 后设置 UiButton 图像
- google-cloud-platform - 如何通过控制台启动 Datalab?
- sql-server - “从字符串转换日期和/或时间时转换失败。” 错误
- python - pytest - 向所有或标记的测试函数添加断言
- angular - POST请求后获取变量的值